我是网络编程的新手,我们在实验室中应该做的第一个程序是一个程序,其中两个系统,客户端和服务器相互发送消息。我的程序没有编译器错误,但无论何时通过网络发送消息,它都无法在另一端正确显示。相反,正在显示一个不可读的框(我认为正在打印垃圾字符串,但不知道为什么)。
代码:
client.c
int main()
{
char server_message[256]="You have reached the server!!\n";
//create a socket
int nw_socket;
nw_socket=socket(AF_INET,SOCK_STREAM,0);
//specify address for socket
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9999);
server_address.sin_addr.s_addr = INADDR_ANY;
//establish a connection
int connection_status = connect(nw_socket, (struct sockaddr *) & server_address, sizeof(server_address));
//check for errors
if(connection_status==-1)
{
perror("There was a problem initiating the connection.\n");
}
else
{
printf("The connection was successful.\n");
}
int send_val = send(nw_socket,server_message,sizeof(server_message),0);
if(send_val==-1)
perror("\nError while sending: ");
//receive data
char data[256];
int recv_val=recv(nw_socket,data,sizeof(data),0);
if(recv_val==-1)
perror("\nError while receiving: ");
printf("The server's response was: %s\n",data );
//close the socket
close(nw_socket);
return 0;
}
server.c
int main()
{
char server_message[256]="You have reached the server!!\n";
//create a new socket
int server_socket=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server_connection;
server_connection.sin_family=AF_INET;
server_connection.sin_port=htons(9999);
server_connection.sin_addr.s_addr=INADDR_ANY;
int bind_val=bind(server_socket, (struct sockaddr *) & server_connection, sizeof(server_connection));
if(bind_val==-1)
perror("\nError while binding: ");
listen(server_socket,6);
int client_socket=accept(server_socket, NULL, NULL);
if(client_socket==-1)
perror("\nError while accepting: ");
int send_val= send(server_socket,server_message,sizeof(server_message),0);
if(send_val==-1)
perror("\nError while sending: ");
char data[256];
recv(server_socket,data,sizeof(data),0);
close(server_socket);
return 0;
}
我该如何解决这个问题?提前谢谢。
答案 0 :(得分:7)
在服务器中发送消息时,您正在使用侦听套接字:
int send_val= send(server_socket,server_message,sizeof(server_message),0);
您应该使用连接到客户端的套接字:
int send_val = send(client_socket,server_message,sizeof(server_message),0);