我的tcp/ip协议的局域网聊天程序,总是无法连接,大神求解
发布网友
发布时间:2022-04-26 11:07
我来回答
共2个回答
热心网友
时间:2022-06-27 17:07
// tcpTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
void main()
{
sockaddr_in tcp;
SOCKET s;
int port = 5001;
SOCKET s1;
char ipp[16] = {"0"};
int len;
char rec[100];
char sen[100];
int isockErr;
sockaddr_in tcpaddr;
//打开winsock
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested=MAKEWORD(2,2);
if(WSAStartup(wVersionRequested,&wsaData)!=0)
{
printf("初始化错误!\n");
system("pause");
return;
}
else
{
printf("初始化正确!\n");
}
if(wsaData.wVersion!=wVersionRequested)
{
WSACleanup();
system("pause");
return;
}
s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
tcp.sin_family=AF_INET;
tcp.sin_port=htons(port);
tcp.sin_addr.s_addr=htons(INADDR_ANY);
if(bind(s,(LPSOCKADDR)&tcp, sizeof(tcp))==SOCKET_ERROR)
{
printf("绑定错误!");
system("pause");
return;
}
else
{
printf("绑定完成!\n");
//system("pause");
}
if(listen(s,3)==0)
{
printf("listen成功!\n");
}
else
{
printf("listen失败!\n");
}
len = sizeof(tcpaddr);
s1 = accept(s,(LPSOCKADDR) &tcpaddr , &len);//这里错误比较严重。
while(1)
{
recv(s1,rec,100,0);
printf("%s\n",rec);
printf("fu师长:\n");
memset(sen, 0, 100);
gets(sen);
send(s1,sen,strlen(sen),0);
//printf("%s\n",sen);
}
closesocket(s);//关闭
WSACleanup();//释放资源的操作
}
热心网友
时间:2022-06-27 17:07
有点复杂~