我有多个客户端连接到服务器。每次服务器向客户端2发送包含客户端1的IP和地址的字符串时,客户端2连接到客户端1并向其发送消息。
服务器和客户端是本地的;他们拥有相同的IP但不同的监听端口。
我收到以下错误:传输端点已经连接。
调试后,我认为这是因为IP地址相同,但我不明白它为什么不通过端口连接。客户端2获取客户端1的正确端口。
(注意:我省略了错误处理)
以下是代码:
sockfd = socket(AF_INET, SOCK_STREAM,0); //the one for the server
sockfd2 = socket(AF_INET, SOCK_STREAM,0); //the one for the client
//creating client
client.sin_family = AF_INET;
client.sin_port = htons(atoi(argv[3])); // the port is read from command line
client.sin_addr.s_addr = INADDR_ANY;
//bind
int b = bind(sockfd2, (struct sockaddr *) &client, sizeof(struct sockaddr));
//listen
listen(sockfd2,1); //only 1 client can connect to this one!
//creating server
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[5])); // the port is read from command line
inet_aton(argv[4], &serv_addr.sin_addr);
connect(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr));
while(1){
... // the client connects to the server and gets the string
destination.sin_family = AF_INET;
destination.sin_addr.s_addr= inet_addr(address);
destination.sin_port = htons(atoi(port));
//this line gives the error
if(connect(sockfd2,(struct sockaddr*)&destination, sizeof(destination)<0)
error("Error connecting");
//the sending
n = send(sockfd2, message, strlen(message), 0);
if(n<0)
error("Error sending");
....
}
答案 0 :(得分:1)
sockfd2
的 connect()
已被绑定,并被指定一个角色(通过listen
)作为服务器套接字。基本上它可以做的唯一有效操作是accept()
传入连接。