Ⅰ 求C語言高手,實現一個簡單的TCPIP程序以實現兩台計算機之間的聊天通信,
你上面給出的代碼其實就是MSDN裡面的演示代碼,不過不完整,只演示了兩個函數的使用,我給你看看我寫的TCP通訊程序,可以在同一個區域網內的兩台不同計算機之間聊天:
這其實就是某本將網路通訊的教程裡面的例子,不過是我自己重寫了一遍,下面給你代碼:
========================
下面是公共代碼:
========================
#ifndef__CINITSOCK__H__
#define__CINITSOCK__H__
#include<winsock2.h>
#include<iphlpapi.h>
#pragmacomment(lib,"ws2_32.lib")
#pragmacomment(lib,"iphlpapi.lib")
classCInitSock
{
public:
CInitSock(intnMinorVer=2,intnMajorVer=2)
{
WSADATAwsData;
WORDwVer=MAKEWORD(nMinorVer,nMajorVer);
if(0!=WSAStartup(wVer,&wsData))exit(0);
}
~CInitSock()
{
WSACleanup();
}
};
#endif
========================
下面是客戶端的代碼:
=======================
#include"CInitSock.h"
#include<iostream>
usingnamespacestd;
CInitSockg_Sock;
voidmain()
{
SOCKETsockClient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==sockClient)
return;
sockaddr_insockAddr;
sockAddr.sin_family=AF_INET;
sockAddr.sin_port=htons(4567);
sockAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
if(-1==connect(sockClient,(sockaddr*)&sockAddr,sizeof(sockAddr)))
{
cout<<"connectfailed"<<endl;
return;
}
while(true)
{
charszBuf[MAX_PATH];
ZeroMemory(szBuf,sizeof(szBuf));
cout<<"YouSay:";
cin>>szBuf;
if(SOCKET_ERROR ==send(sockClient,szBuf,MAX_PATH,0))
{
cout<<"sendfailed"<<endl;
return;
}
intnRecvLen=recv(sockClient,szBuf,MAX_PATH,0);
if(nRecvLen>0)
{
//szBuf[nRecvLen]='