C语言 socket 编写简单服务端客户端通信问题
大家好,感谢你的回复。我用c 写了一个socket通信的小程序,写好了服务端和客户端,可遇到个问题,就是每次启动客户端只能发送第一条消息,之后服务端就不能再收到消息了。
Talk is cheak , show me the code.
服务端代码:
#include<stdlib.h>
#include<WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int main(){
WSADATA wsd;
SOCKET sockServer;
SOCKADDR_IN serveraddr;// 服务端套接字 该结构中包含了要结合的地址和端口号
SOCKET sockClient;
SOCKADDR_IN clientaddr;
WSAStartup(MAKEWORD(2,2),&wsd);//初始化网络接口
sockServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);//创建服务器socket
if (sockServer != -1 && sockServer != INVALID_SOCKET){
printf("Socket has been created :%d", sockServer);
}
else{
printf("Socket create failed.");
exit(0);
}
serveraddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(6000);//绑定端口6000
int bindInfo = bind(sockServer, (SOCKADDR*)&serveraddr, sizeof(SOCKADDR));
char recvBuf;
int len = sizeof(SOCKADDR);
listen(sockServer, 5);//5为等待连接数
while (1){
sockClient = accept(sockServer, (SOCKADDR*)&clientaddr, &len);
//接收客户端数据
recv(sockClient, recvBuf, strlen(recvBuf)+1, MSG_PEEK);
printf("to me:%s\n",recvBuf);
memset(recvBuf, 0, 100);
}
closesocket(sockClient);
system("pause");
return 0;
}客户端代码:
#include<winsock2.h>
#include<stdio.h>
#pragma comment(lib, "ws2_32.lib")
void main()
{
WSADATA wsaData;
SOCKET sockClient;//客户端Socket
SOCKADDR_IN addrServer;//服务端地址
WSAStartup(MAKEWORD(2, 2), &wsaData);
char message = "HelloSocket!";
//定义要连接的服务端地址
addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//目标IP(127.0.0.1是回送地址)
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(6000);//连接端口6000
//新建客户端socket
sockClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int s = 0;
s = connect(sockClient, (SOCKADDR*)&addrServer, sizeof(SOCKADDR));
while (1){
//发送数据
int a = send(sockClient, message, strlen(message) + 1, 0);
printf("to server:");
scanf("%s", message);
}
//关闭socket
closesocket(sockClient);
WSACleanup();
}求懂的高手来解答一下。
谢谢了!
应该用多线程或者多进程,,,过两天给你源代码 我已找到原因了, recv(sockClient, recvBuf, strlen(recvBuf)+1, MSG_PEEK); 这句改为
recv(sockClient, recvBuf, strlen(recvBuf)+1, 0); 就OK了
页:
[1]