请帮帮我
客户:
#include<stdio.h> //printf
#include<string.h> //strlen
#include<sys/socket.h> //socket
#include<arpa/inet.h> //inet_addr
int main(int argc , char *argv[])
{
int sock;
struct sockaddr_in server;
char message[1000] , server_reply[2000];
//Create socket
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
}
puts("Socket created");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
//Connect to remote server
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
perror("connect failed. Error");
return 1;
}
puts("Connected\n");
//keep communicating with server
while(1)
{
printf("Enter message : ");
scanf("%s" , message);
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
memset(message,0,sizeof(message));
//Receive a reply from the server
}
close(sock);
return 0;
}
服务器:
#include<stdio.h>
#include<string.h> //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h> //write
int main(int argc , char *argv[])
{
int socket_desc , client_sock , c , read_size;
struct sockaddr_in server , client;
char client_message[2000];
//Create socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
puts("Socket created");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
//Bind
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
{
//print the error message
perror("bind failed. Error");
return 1;
}
puts("bind done");
//Listen
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
//accept connection from an incoming client
client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
if (client_sock < 0)
{
perror("accept failed");
return 1;
}
puts("Connection accepted");
//Receive a message from client
while( (read_size = recv(client_sock , client_message , 2000 , 0)) > 0 )
{
if(read_size == 0)
{
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1)
{
perror("recv failed");
}
//Send the message back to client
puts(client_message);
fflush(stdout);
}
return 0;
}
来自网站的源代码。我尝试并成功连接并发送消息。问题是我将客户端连接到服务器。然后我用ctrl + c关闭服务器。我尝试发送消息,为什么我的消息发送成功? (当服务器结束时)。但是,当我再次尝试发送消息时,连接结束。请帮我。我想只发送一次,连接结束。不是两次。
答案 0 :(得分:0)
这会发生什么:您的代码退出是因为引发了SIG_PIPE以指示发送错误。你没有信号捕获器,因此默认操作是静默退出!
试试这个send(sock , message , strlen(message) ,MSG_NOSIGNAL)
并阅读信号
答案 1 :(得分:0)
但是如何只发送一次,连接结束(服务器关闭ctrl + c)? 不要两次发送。
虽然您的客户端没有recv()
呼叫,但在服务器终止后第一次send()
呼叫后,您仍然可以通过获取待处理的套接字立即检测到 Broken pipe getsockopt(…, SOL_SOCKET, SO_ERROR, …)
错误,如this answer to "How to find the socket connection state in C?"中所示
如果以这种方式返回错误,您可以break
循环和close()
套接字。