我用Winsock创建了两个程序,一个服务器程序和一个客户端程序。当我在Windows机器上(当然是在其他cmd窗口中)执行它们时,我能够从客户端收到消息。当我尝试在另一台计算机上运行客户端时,收到一条消息,说明套接字已成功创建,但未发送任何消息。相反,服务器只是继续侦听,而客户端没有进一步响应。没有错误代码(甚至没有超时过期之类的东西)。
我试图更改端口号(从某个随机端口更改为端口80),但这无济于事。我还关闭了服务器端和客户端的防火墙,但这也无济于事。
我为客户提供的代码是:
#include <winsock2.h>
#include <stdio.h>
#include <iostream>
int startWinsock(void);
int main()
{
long rc;
SOCKET s;
char buf[250] = "HELLO";
SOCKADDR_IN addr;
rc=startWinsock();
if(rc!=0){
printf("Error: startWinsock, error code: %d\n",rc);
return 1;
}
else{
printf("Winsock started!\n");
}
s=socket(AF_INET,SOCK_STREAM,0);
if(s==INVALID_SOCKET){
printf("Error: Could not create Socket: %d\n",WSAGetLastError());
return 1;
}
else{
printf("Socket created!\n");
}
memset(&addr,0,sizeof(SOCKADDR_IN)); // initialise to 0
addr.sin_family=AF_INET;
addr.sin_port=htons(80);
addr.sin_addr.s_addr=inet_addr("myip"); // address is the IP adress of the PC where the server program runs
rc=connect(s,(SOCKADDR*)&addr,sizeof(SOCKADDR));
if(rc==SOCKET_ERROR){
printf("Error: could not connect: %d\n",WSAGetLastError());
return 1;
}
else{
printf("conected");
}
rc=send(s,buf,strlen(buf),0);
}
buf[rc]='\0';
closesocket(s);
WSACleanup();
return 0;
}
int startWinsock(void)
{
WSADATA wsa;
return WSAStartup(MAKEWORD(2,0),&wsa);
}
并在服务器端:
#include <windows.h>
#include <winsock2.h>
#include <stdio.h>
int startWinsock(void);
int main()
{
long rc;
char buf[250];
SOCKET acceptSocket;
SOCKET connectedSocket;
SOCKADDR_IN addr;
rc=startWinsock();
if(rc!=0){
printf("Error startWinsock: %d\n",rc);
return 1;
}
else
{
printf("Winsock started!\n");
}
acceptSocket=socket(AF_INET,SOCK_STREAM,0);
if(acceptSocket==INVALID_SOCKET){
printf("Error: Could not create Socket: %d\n",WSAGetLastError());
return 1;
}
else{
printf("Socket created!\n");
}
memset(&addr,0,sizeof(SOCKADDR_IN));
addr.sin_family=AF_INET;
addr.sin_port=htons(80);
addr.sin_addr.s_addr=ADDR_ANY;
rc=bind(acceptSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR_IN));
if(rc==SOCKET_ERROR){
printf("Error: bind: %d\n",WSAGetLastError());
return 1;
}
else{
printf("Socket binded to port 80\n");
}
rc=listen(acceptSocket,10);
if(rc!=0){
printf("Error: listen: %d\n",WSAGetLastError());
return 1;
}
else{
printf("acceptSocket in listen mode....\n");
}
connectedSocket=accept(acceptSocket,NULL,NULL);
if(connectedSocket==INVALID_SOCKET){
printf("Error: accept: %d\n",WSAGetLastError());
return 1;
}
else{
printf("New connection accepted!\n");
}
rc=recv(connectedSocket,buf,250,0);
buf[rc]='\0';
printf("Client sendet: %s\n",&buf);
closesocket(acceptSocket);
closesocket(connectedSocket);
WSACleanup();
return 0;
}
int startWinsock(void)
{
WSADATA wsa;
return WSAStartup(MAKEWORD(2,0),&wsa);
}