我正在使用C中的 socket编程方法来开发简单的聊天室程序。我已经实现了客户端可以连接到服务器并将消息发送到服务器,并且服务器应该将消息分发给其他人。
但是当我尝试测试我的程序并试图使两个客户端通信时,会发生一些奇怪的事情。如果执行以下步骤,将会发生奇怪的事情。
更多点:
这是我的问题的屏幕截图(聊天室:左是服务器,右是两个客户端):
这是我的client.c和server.c代码,我已经指出了发生此问题的位置。
客户端C
/* tcp-client.c */
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
//send the message to the server any time terminal get input
void* Send(void* Socked)
{
char sender[80];
//save the socked into a int pointer
int *SockedCopy = Socked;
while(fgets(sender, sizeof(sender), stdin)){
//whenever enter a string, send it
int messageSize = strlen(sender) + 1;
write(*SockedCopy, &messageSize, sizeof(int));
int i = write(*SockedCopy, sender, messageSize); //both work when sending message
printf("write over! the write() returns %d\n", i);
//check whether this is a quit message
if(strcmp(sender, "q!") == 0)
exit(1);
}
}
//receive message from server
void* Receive(void* Socked)
{
int *SockedCopy = Socked;
char Receiver[80];
while(1){
//read message continuosly
int reveiverEnd = 0;
reveiverEnd = read (*SockedCopy, Receiver, 1000);
Receiver[reveiverEnd] = '\0';
fputs(Receiver, stdout);
Receiver[0] = '\0';
}
}
int main ()
{
int sockfd, n;
pthread_t threadSend;
pthread_t threadReceive;
struct sockaddr_in serv, cli;
char rec[1000];
char send[80];
//input UserName
printf("Input Username:" );
fgets(send, sizeof(send), stdin);
send[strlen(send) - 1] = '\0';
int MessageSize = strlen(send);
//create socked
sockfd = socket (PF_INET, SOCK_STREAM, 0);
//create server information
bzero (&serv, sizeof (serv));
serv.sin_family = PF_INET;
serv.sin_port = htons (8888);
serv.sin_addr.s_addr = inet_addr ("127.0.0.1" /*local machine*/);
//connect to the server
connect (sockfd, (struct sockaddr *) &serv, sizeof (struct sockaddr));
//send the user name to the server
write(sockfd, &MessageSize, sizeof(int));
write (sockfd, send, sizeof(send));
//get successfully connecting message
n = read (sockfd, rec, 1000);//n marks real length
rec[n] = '\0';
fputs(rec, stdout);
send[0] = '\0';
//open send thread
pthread_create(&threadSend, 0, Send, &sockfd);
//open receiving message thread
pthread_create(&threadReceive, 0, Receive, &sockfd);
//close socked and close two threads
for(int i = 0; i < 100; ++i)
sleep(100000);
pthread_exit(&threadSend);
pthread_exit(&threadReceive);
close(sockfd);
return 0;
}
SERVER.C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <unistd.h>
#include <unistd.h>
pthread_t thread;
pthread_t threadClient[100];
int ServerSock;
//Every client's information
typedef struct
{
int sock;
char UserName[16];
struct sockaddr address;
int addr_len;
} connection_t;
static connection_t conn[100];
//this function distributes the messsage/status of single client to the other
//Info is the message needed to be distributed
int SendInfo(void* Info)
{
char *info = Info;
for(int i = 0; i < 100; ++i)
//send to the client that exists and doesn't quit room
if(conn[i].addr_len != -1 && conn[i].addr_len != 0){
if(send (conn[i].sock, info , strlen(info) + 1, 0) == -1)
printf("error occured, send to %s fail", conn[i].UserName);
printf("send %s to %s successfully!\n", info, conn[i].UserName);
}
return 0;
}
//This function deals with single client, aim to receive message from this client
//and then send them to another using SendIinfo
void* Receive(void* clientnumber)
{
int* Clientnumber = clientnumber;
while(1)
{
//read the message from the client
char *Buffer;
int messageLen = 0;
read(conn[*Clientnumber].sock, &messageLen, sizeof(int));
printf("receive from %d\n", messageLen);
if(messageLen > 0)
{
Buffer = (char *)malloc((messageLen+1)*sizeof(char));
read(conn[*Clientnumber].sock, Buffer, messageLen); // the program stucks here and don't know why
if(Buffer[0] != ':') continue;
Buffer[messageLen] = '\0';
//whether the client want to quit
if( Buffer[1] == 'q' && Buffer[2] == '!' )
{
//constitute quit message and delete this client
char quit[] = " quit the chat room";
char quitMessage[20];
quitMessage[0] = '\0';
strcat(conn[*Clientnumber].UserName, quit);
SendInfo(quitMessage);
conn[*Clientnumber].addr_len = -1;
pthread_exit(&threadClient[*Clientnumber]);
}
else{
//constitute the message
char begin[] = " says";
char messageDistribute[200];
messageDistribute[0] = '\0';
strcat(messageDistribute, conn[*Clientnumber].UserName);
strcat(messageDistribute, begin);
strcat(messageDistribute, Buffer);
SendInfo(messageDistribute);
}
free(Buffer);
}
else
continue;
}
}
//aim to accept whenever there is a client trying to connect
void * process(void * ptr)
{
pthread_t clientThread[100];
char * buffer;
int len;
//the number of the client connecting now
int clientNumber = 0;
long addr = 0;
while(1){
//waiting to be connected
if(clientNumber < 100)
{
conn[clientNumber].sock = accept(ServerSock, &conn[clientNumber].address, &conn[clientNumber].addr_len);
}
else
break;
//the length of the message
read(conn[clientNumber].sock, &len, sizeof(int));
if (len > 0)
{
//multiple information of a client
addr = (long)((struct sockaddr_in *)&conn[clientNumber].address)->sin_addr.s_addr;
buffer = (char *)malloc((len+1)*sizeof(char));
buffer[len] = 0;
read(conn[clientNumber].sock, buffer, len);
//send success message to the client
send (conn[clientNumber].sock, "You have entered the chatroom, Start CHATTING Now!\n", 51, 0);
//save client's nick name
strcpy(conn[clientNumber].UserName, buffer);
printf("User <%s> has entered the Chatroom!\n", conn[clientNumber].UserName);
printf("There are %d people in Chatroom now!\n",clientNumber+1);
free(buffer);
//create a thread dealing the messages from a single client
int number = clientNumber;
pthread_create(&threadClient[clientNumber], 0, Receive, &number);
}
clientNumber += 1;
}
pthread_exit(0);
}
int main(int argc, char ** argv){
struct sockaddr_in address;
int port = 8888;
connection_t * connection;
//create socked
ServerSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//bind the socked to a port
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
if (bind(ServerSock, (struct sockaddr *)&address, sizeof(struct sockaddr_in)) < 0)
{
fprintf(stderr, "error: cannot bind socket to port %d\n", port);
return -4;
}
//listen for connections
listen(ServerSock, 100);
printf("the server is ready and listening\n");
//creating a thread dealing with connections
pthread_create(&thread, 0, process, (void *)connection);
//keep this program working
for(int i = 0; i < 100; ++i)
sleep(10000);
//close socked and thread
pthread_detach(thread);
close(ServerSock);
return 0;
}
这是用于学术作业。
答案 0 :(得分:0)
您的问题根本不是网络问题,而是您如何将clientnumber
参数传递到Receive
线程的错误:
if (len > 0)
{
[...]
int number = clientNumber;
pthread_create(&threadClient[clientNumber], 0, Receive, &number);
} // number gets destroyed here
请注意,在上面的代码中,number
是局部变量,这意味着它将在范围退出时(即,一旦执行到达上面的}
行)被销毁。
但是,您正在将指向number
(即&number
)的指针传递到Receive线程,并且您的Receive线程尝试使用该指针来查找有关客户端的数据。这意味着Receive
线程正在取消引用一个悬空指针,该指针将引发未定义的行为。 (在这种情况下,我看到的是程序会在短时间内工作,然后停止工作,因为内存位置Clientnumber
指向的位置已被其他一些数据覆盖,因此下次Receive
线程尝试解除对指针的引用,最终导致查看错误的数据,因此在错误的套接字fd上调用read()
...但是从原理上讲,任何事情都可能发生,因为一旦调用未定义的行为,所有投注均关闭)
在任何情况下,解决此问题的一种简单方法是直接将指针传递到connection_t
对象,而不是传递索引,即:
pthread_create(&threadClient[clientNumber], 0, Receive, &conn[clientNumber] );
....然后可以直接在Receive
线程中使用该指针:
void* Receive(void* arg)
{
connection_t * conn = (connection_t *) arg;
[...]
int r = read(conn->sock, &messageLen, sizeof(int));
以这种方式执行操作不会调用未定义的行为,因为connection_t conn[100];
数组被声明为静态/全局数组,因此保证其中的对象在进程退出之前不会被破坏。
如果仍然需要从clientNumber
内部访问Receive()
索引值,则可以将该值添加为connection_t
结构定义中的另一个字段。