int main(int argc, char *argv[]) { int sock; /* Socket */ struct sockaddr_in broadcastAddr; /* Broadcast Address */ /* Create a best-effort datagram socket using UDP */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { perror("socket failed"); exit(EXIT_FAILURE); } /* Construct bind structure */ memset(&broadcastAddr, 0, sizeof(broadcastAddr)); /* Zero out structure */ broadcastAddr.sin_family = AF_INET; /* Internet address family */ broadcastAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ broadcastAddr.sin_port = htons(PORT); /* Broadcast port */ /* Bind to the broadcast port */ if (bind(sock, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } char recvString[MAXRECVSTRING + 1]; int recvStringLen; int count = 0; while(1) { if ((recvStringLen = recvfrom(sock, recvString, MAXRECVSTRING, 0, NULL, 0)) < 0) { perror("recvfrom failed"); exit(EXIT_FAILURE); } switch(recvString[0]) { case '1': printf("S1\n"); break; case '2': printf("S2\n"); break; case '3': printf("S3\n"); break; default: continue; } } close(sock); exit(0); }
时间: 2024-02-14 16:23:47 浏览: 141
这是一个使用UDP协议的C语言网络编程例子,通过创建一个socket和绑定一个广播地址,可以接收从其他主机发送的广播消息。在while循环中,通过recvfrom函数来接收消息,并通过switch语句来判断接收到的消息类型,并进行相应的处理。如果接收到的消息不是指定的类型,则继续等待接收下一条消息。最后,通过close函数关闭socket连接。
相关问题
帮我用c++写windows下基于socket通信的聊天室服务器与客户端实现的代码 完成功能: 1.用户注册功能; 2.两个用户服务器发送私密消息; 3.用户创建一个或多个聊天群组; 4.用户加入群组、在群组内发送消息、离开群组; 5.用户之间的聊天信息通过服务器端转发;
以下是一个简单的基于socket通信的聊天室服务器与客户端实现的代码,仅供参考:
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define MAX_CLIENTS 10
#define MAX_USERNAME_LEN 20
#define MAX_MESSAGE_LEN 256
SOCKET client_sockets[MAX_CLIENTS];
char client_usernames[MAX_CLIENTS][MAX_USERNAME_LEN];
int num_clients = 0;
typedef struct {
char name[MAX_USERNAME_LEN];
SOCKET socket;
} client_info_t;
typedef struct {
char name[MAX_USERNAME_LEN];
int num_clients;
client_info_t clients[MAX_CLIENTS];
} chatroom_t;
chatroom_t chatrooms[MAX_CLIENTS];
int num_chatrooms = 0;
void error(char *msg) {
perror(msg);
exit(1);
}
void add_client_to_chatroom(char *chatroom_name, client_info_t client) {
int i;
for (i = 0; i < num_chatrooms; i++) {
if (strcmp(chatroom_name, chatrooms[i].name) == 0) {
chatrooms[i].clients[chatrooms[i].num_clients++] = client;
return;
}
}
// Chatroom not found, create new chatroom
chatroom_t new_chatroom;
strcpy(new_chatroom.name, chatroom_name);
new_chatroom.clients[0] = client;
new_chatroom.num_clients = 1;
chatrooms[num_chatrooms++] = new_chatroom;
}
void remove_client_from_chatroom(char *chatroom_name, SOCKET client_socket) {
int i, j;
for (i = 0; i < num_chatrooms; i++) {
if (strcmp(chatroom_name, chatrooms[i].name) == 0) {
for (j = 0; j < chatrooms[i].num_clients; j++) {
if (chatrooms[i].clients[j].socket == client_socket) {
// Remove client from chatroom
chatrooms[i].num_clients--;
while (j < chatrooms[i].num_clients) {
chatrooms[i].clients[j] = chatrooms[i].clients[j+1];
j++;
}
return;
}
}
return; // Client not found in chatroom
}
}
}
void broadcast_message(char *message, SOCKET sender_socket) {
int i;
for (i = 0; i < num_clients; i++) {
if (client_sockets[i] != sender_socket) {
send(client_sockets[i], message, strlen(message), 0);
}
}
}
void send_private_message(char *message, char *recipient) {
int i;
for (i = 0; i < num_clients; i++) {
if (strcmp(recipient, client_usernames[i]) == 0) {
send(client_sockets[i], message, strlen(message), 0);
return;
}
}
}
void send_chatroom_message(char *message, char *chatroom_name, SOCKET sender_socket) {
int i, j;
for (i = 0; i < num_chatrooms; i++) {
if (strcmp(chatroom_name, chatrooms[i].name) == 0) {
for (j = 0; j < chatrooms[i].num_clients; j++) {
if (chatrooms[i].clients[j].socket != sender_socket) {
send(chatrooms[i].clients[j].socket, message, strlen(message), 0);
}
}
return;
}
}
}
void *handle_client(void *arg) {
SOCKET client_socket = *(SOCKET *)arg;
char username[MAX_USERNAME_LEN];
// Receive username from client
int n = recv(client_socket, username, MAX_USERNAME_LEN, 0);
if (n < 0) {
error("ERROR receiving username from client");
}
username[n] = '\0';
printf("New client connected: %s\n", username);
// Add client to list of clients
client_sockets[num_clients] = client_socket;
strcpy(client_usernames[num_clients], username);
num_clients++;
// Send welcome message to client
char welcome_message[MAX_MESSAGE_LEN];
sprintf(welcome_message, "Welcome to the chatroom, %s!\n", username);
send(client_socket, welcome_message, strlen(welcome_message), 0);
while (1) {
// Receive message from client
char message[MAX_MESSAGE_LEN];
n = recv(client_socket, message, MAX_MESSAGE_LEN, 0);
if (n < 0) {
error("ERROR receiving message from client");
}
message[n] = '\0';
// Parse message
if (strncmp(message, "/pm", 3) == 0) {
// Private message
char recipient[MAX_USERNAME_LEN];
char private_message[MAX_MESSAGE_LEN];
sscanf(message + 4, "%s %[^\t\n]", recipient, private_message);
char pm_message[MAX_MESSAGE_LEN];
sprintf(pm_message, "%s (private): %s\n", username, private_message);
send_private_message(pm_message, recipient);
} else if (strncmp(message, "/join", 5) == 0) {
// Join chatroom
char chatroom_name[MAX_USERNAME_LEN];
sscanf(message + 6, "%s", chatroom_name);
char join_message[MAX_MESSAGE_LEN];
sprintf(join_message, "%s joined chatroom %s\n", username, chatroom_name);
send_chatroom_message(join_message, chatroom_name, client_socket);
client_info_t client;
strcpy(client.name, username);
client.socket = client_socket;
add_client_to_chatroom(chatroom_name, client);
} else if (strncmp(message, "/leave", 6) == 0) {
// Leave chatroom
char chatroom_name[MAX_USERNAME_LEN];
sscanf(message + 7, "%s", chatroom_name);
char leave_message[MAX_MESSAGE_LEN];
sprintf(leave_message, "%s left chatroom %s\n", username, chatroom_name);
send_chatroom_message(leave_message, chatroom_name, client_socket);
remove_client_from_chatroom(chatroom_name, client_socket);
} else {
// Broadcast message to all clients
char broadcast_message[MAX_MESSAGE_LEN];
sprintf(broadcast_message, "%s: %s", username, message);
broadcast_message(broadcast_message, client_socket);
}
}
}
int main(int argc, char *argv[]) {
WSADATA wsaData;
int i, portno;
if (argc < 2) {
fprintf(stderr, "Usage: %s port\n", argv[0]);
exit(1);
}
portno = atoi(argv[1]);
// Initialize Winsock
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
error("WSAStartup failed");
}
// Create socket
SOCKET server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == INVALID_SOCKET) {
error("ERROR creating socket");
}
// Bind socket to port
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(portno);
if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
error("ERROR binding socket");
}
// Listen for connections
if (listen(server_socket, MAX_CLIENTS) == SOCKET_ERROR) {
error("ERROR listening for connections");
}
// Accept connections
struct sockaddr_in client_addr;
int client_addr_len = sizeof(client_addr);
while (1) {
// Accept new connection
SOCKET client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_socket == INVALID_SOCKET) {
error("ERROR accepting connection");
}
// Spawn new thread to handle client connection
HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)handle_client, &client_socket, 0, NULL);
if (thread == NULL) {
error("ERROR creating thread");
}
}
// Close socket
closesocket(server_socket);
// Cleanup Winsock
WSACleanup();
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#define MAX_USERNAME_LEN 20
#define MAX_MESSAGE_LEN 256
void error(char *msg) {
perror(msg);
exit(1);
}
void *receive_messages(void *arg) {
SOCKET server_socket = *(SOCKET *)arg;
while (1) {
char message[MAX_MESSAGE_LEN];
int n = recv(server_socket, message, MAX_MESSAGE_LEN, 0);
if (n < 0) {
error("ERROR receiving message from server");
}
message[n] = '\0';
printf("%s", message);
}
}
int main(int argc, char *argv[]) {
WSADATA wsaData;
int portno, n;
char username[MAX_USERNAME_LEN], message[MAX_MESSAGE_LEN];
struct sockaddr_in server_addr;
SOCKET server_socket;
if (argc < 3) {
fprintf(stderr, "Usage: %s hostname port\n", argv[0]);
exit(1);
}
portno = atoi(argv[2]);
// Initialize Winsock
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
error("WSAStartup failed");
}
// Create socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == INVALID_SOCKET) {
error("ERROR creating socket");
}
// Connect to server
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(portno);
if (inet_pton(AF_INET, argv[1], &server_addr.sin_addr) <= 0) {
error("ERROR invalid address");
}
if (connect(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
error("ERROR connecting to server");
}
// Receive welcome message from server
n = recv(server_socket, message, MAX_MESSAGE_LEN, 0);
if (n < 0) {
error("ERROR receiving message from server");
}
message[n] = '\0';
printf("%s", message);
// Send username to server
printf("Enter username: ");
fgets(username, MAX_USERNAME_LEN, stdin);
username[strcspn(username, "\n")] = '\0';
n = send(server_socket, username, strlen(username), 0);
if (n < 0) {
error("ERROR sending username to server");
}
// Create thread to receive messages
HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)receive_messages, &server_socket, 0, NULL);
if (thread == NULL) {
error("ERROR creating receive thread");
}
// Send messages
while (1) {
fgets(message, MAX_MESSAGE_LEN, stdin);
message[strcspn(message, "\n")] = '\0';
if (strcmp(message, "/quit") == 0) {
break;
}
n = send(server_socket, message, strlen(message), 0);
if (n < 0) {
error("ERROR sending message to server");
}
}
// Close socket
closesocket(server_socket);
// Cleanup Winsock
WSACleanup();
return 0;
}
```
C/C++ 编写一个服务器与客户端的群聊
以下是一个简单的基于TCP协议的服务器与客户端的群聊实现。该程序使用了多线程来支持多个客户端同时连接。
服务器代码(chat_server.c):
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024
int clients[MAX_CLIENTS];
int num_clients = 0;
pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;
void broadcast_message(char *message, int sender) {
pthread_mutex_lock(&clients_mutex);
for (int i = 0; i < num_clients; i++) {
if (clients[i] != sender) {
send(clients[i], message, strlen(message), 0);
}
}
pthread_mutex_unlock(&clients_mutex);
}
void *client_thread(void *arg) {
int client_fd = *(int*)arg;
char buffer[BUFFER_SIZE];
pthread_mutex_lock(&clients_mutex);
clients[num_clients++] = client_fd;
pthread_mutex_unlock(&clients_mutex);
while (1) {
int bytes_read = recv(client_fd, buffer, BUFFER_SIZE, 0);
if (bytes_read <= 0) {
pthread_mutex_lock(&clients_mutex);
for (int i = 0; i < num_clients; i++) {
if (clients[i] == client_fd) {
clients[i] = -1;
break;
}
}
pthread_mutex_unlock(&clients_mutex);
close(client_fd);
return NULL;
}
buffer[bytes_read] = '\0';
broadcast_message(buffer, client_fd);
}
}
int main(int argc, char *argv[]) {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_len = sizeof(client_addr);
pthread_t tid;
if (argc != 2) {
printf("Usage: %s <port>\n", argv[0]);
exit(1);
}
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
perror("socket");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(atoi(argv[1]));
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("bind");
exit(1);
}
if (listen(server_fd, MAX_CLIENTS) < 0) {
perror("listen");
exit(1);
}
printf("Server listening on port %s...\n", argv[1]);
while (1) {
client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &client_len);
if (client_fd < 0) {
perror("accept");
exit(1);
}
pthread_create(&tid, NULL, client_thread, &client_fd);
}
return 0;
}
```
客户端代码(chat_client.c):
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
int client_fd, port;
char buffer[BUFFER_SIZE];
struct hostent *server;
struct sockaddr_in server_addr;
if (argc != 3) {
printf("Usage: %s <hostname> <port>\n", argv[0]);
exit(1);
}
port = atoi(argv[2]);
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr, "Error: no such host\n");
exit(1);
}
client_fd = socket(AF_INET, SOCK_STREAM, 0);
if (client_fd < 0) {
perror("socket");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
memcpy(&server_addr.sin_addr.s_addr, server->h_addr, server->h_length);
server_addr.sin_port = htons(port);
if (connect(client_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("connect");
exit(1);
}
printf("Connected to server %s:%d\n", argv[1], port);
while (1) {
printf("> ");
fgets(buffer, BUFFER_SIZE, stdin);
send(client_fd, buffer, strlen(buffer), 0);
}
return 0;
}
```
编译方法:
```
gcc -o chat_server chat_server.c -lpthread
gcc -o chat_client chat_client.c
```
运行方法:
```
./chat_server <port>
./chat_client <hostname> <port>
```
其中,`<port>`是服务器监听的端口号,`<hostname>`是服务器的主机名或IP地址。客户端连接服务器后,可以输入任意文本并发送到服务器,服务器会将该文本广播给所有连接的客户端。
阅读全文