我刚开始学习如何编写套接字但有问题我无法解决。
所以我试图创建一个telnet客户端,并且我已经成功接收到来自服务器的第一条消息,但在此接收行之后,我的程序被卡住了,不会做任何其他事情。甚至不是简单的printf系列。
提前谢谢, 瑞奇这是代码:
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error_msg(char msg[256]){
printf("error at %s\n", msg);
}
void main(){
struct sockaddr_in serv_addr;
char buffer[2048], server_reply[2048];
printf("trying to connect to []...\n");
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd<0) error_msg("socket");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("192.168.0.1");
serv_addr.sin_port = htons(23);
int conn = connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr));
if(conn<0) error_msg("connect");
printf("connected to server\n");
bzero(server_reply, 2048);
bzero(buffer, 2048);
while(1){
int n_recv = recv(sockfd , server_reply , sizeof(server_reply) , 0);
if(n_recv > 0){
printf("%s", server_reply);
sleep(1);
scanf("%s" , buffer);
int n_send = send(sockfd , buffer , sizeof(buffer), 0);
if(n_send < 0) printf("send error, server is not responding...\n");
}
if(n_recv < 0) printf("recv error, server is not responding...\n");
}
close(sockfd);
}
答案 0 :(得分:0)
如果不确切知道返回值是什么,远程端似乎可能已关闭连接:
http://linux.die.net/man/2/recv
The return value will be 0 when the peer has performed an orderly shutdown.
查看我对您的问题的评论并发布该数据,我应该能够提供更多帮助。