我正在尝试在C中创建一个线程聊天服务器,但是无法弄清楚如何不将消息回显给用户。我希望能够连接两个或更多客户端,并通过我的服务器相互聊天。
我哪里错了:
#include<stdio.h>
#include<string.h> //strlen
#include<stdlib.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
#include<pthread.h> //for threading , link with lpthread
#include<errno.h>
void *connectionHandler(void * soc_desc);
typedef struct {
int reader;
int writer;
}args;
int main(int arc, char* argv[]){
int *new_socket;
int socFD;
int client_sock;
struct sockaddr_in serveraddr;
struct sockaddr_in clientaddr;
args t1args, t2args;
int listenFd;
//socklen_t clientSize= size(struct sockaddr_in);
int c;
int acceptFD;
int client_sockets[2];
socFD=socket(AF_INET, SOCK_STREAM, 0);
puts("Socket created");
bzero((char*) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family= AF_INET;
serveraddr.sin_addr.s_addr=INADDR_ANY;
serveraddr.sin_port= htons(2000);
bind(socFD, (struct sockaddr*) &serveraddr, sizeof(serveraddr));
puts("bind done");
listen(socFD, 3);
puts("Waiting for incoming connections...");
c= sizeof(struct sockaddr_in);
while((client_sock=accept(socFD, (struct sockaddr *)&clientaddr,(socklen_t *)&c)))
{
printf("%d", client_sock);
puts("IN WHILE LOOP");
pthread_t t1;
new_socket= malloc(1);
*new_socket=client_sock;
if(pthread_create(&t1, NULL, connectionHandler, (void *)new_socket)<0){
perror("Could not create thread");
return -1;
}
}
if(client_sock < 0)
{
perror("accept failed");
return -1;
}
return 0;
}
void *connectionHandler(void * soc_desc)
{
//Get the socket descriptor
// args *temp= (args*)soc_desc;
int sock= *(int*)soc_desc;
int read_size;
char *message , client_message[2000];
char buff[80];
/*
while(1){
bzero(buff,sizeof(buff));
recv(temp->reader,buff,sizeof(buff),0);
send(temp->writer,buff,sizeof(buff),0);
}*/
//Receive a message from client
while( (read_size = recv(sock , client_message , 2000 , 0)) >0 )
{
//Send the message back to client
write(sock, client_message ,strlen(client_message));
}
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
//Free the socket pointer
free(soc_desc);
return 0;
}
答案 0 :(得分:5)
http://beej.us/guide/bgnet/html/single/bgnet.html
我大约3年前用C做套接字编程,这就是我所遵循的。帮助了我很多。