写个客户端程序
#include "winsock2.h"
#include "iostream"
using namespace std;
DWORD WINAPI RecvThread(LPVOID pParam);
DWORD WINAPI SendThread(LPVOID pParam);
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
//使要求的版本为1.1
int err;
wVersionRequested=MAKEWORD(1,1);
err=WSAStartup(wVersionRequested, &wsaData);
if (err!=0)
{
//用户没有找到一个可以使用的DLL,返回
perror("there is no DLL to use");
return;
}
//确保Windows Sockets DLL支持1.1。
if ( (LOBYTE(wsaData.wVersion)!=1) || (HIBYTE(wsaData.wVersion)!=1) )
{
perror("there is not right DLL");
WSACleanup();
return;
}
cout<<"请输入要连接的主机的IP地址:";
char IP[16];
cin>>IP;
SOCKET s;
s=socket(AF_INET,SOCK_STREAM,0);
if(s<0)
{
cout<<"Invalid socket!"< }
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(1500);
sin.sin_addr.s_addr=inet_addr(IP);
if(connect(s,(sockaddr *)&sin,sizeof(sockaddr))==0)
{
cout<<"连接成功!"< }
CreateThread(NULL,0,RecvThread,&s,0,NULL);
CreateThread(NULL,0,SendThread,&s,0,NULL);
while(WSAGetLastError()!=10054)
{
Sleep(5000);
}
}
DWORD WINAPI RecvThread(LPVOID pParam)
{
SOCKET* c=(SOCKET *)pParam;
char msg[1024];
int msglen=1025;
while(true)
{
if(WSAGetLastError()==10054)
{
exit(1);
}
memset(msg,0,sizeof(msg));
int len=recv(*c,msg,msglen,0);
if(len!=SOCKET_ERROR)
{
cout< }
cout<<"Me:";
}
return 0;
}
DWORD WINAPI SendThread(LPVOID pParam)
{
SOCKET* c=(SOCKET *)pParam;
char msg[1024];
while(true)
{
memset(msg,0,sizeof(msg));
cout<<"Me:";
cin.getline(msg,sizeof(msg));
int len=send(*c,msg,strlen(msg)+1,0);
if(len==SOCKET_ERROR)
{
cout<<"发送失败!"< }
}
return 0;
}
以上程序可以编译成功,但是在执行的时候会出错:
--------------------Configuration: Client - Win32 Debug--------------------
Linking...
Client.obj : error LNK2001: unresolved external symbol
Client.obj : error LNK2001: unresolved external symbol
Client.obj : error LNK2001: unresolved external symbol
Client.obj : error LNK2001: unresolved external symbol
Client.obj : error LNK2001: unresolved external symbol
Client.obj : error LNK2001: unresolved external symbol
Client.obj : error LNK2001: unresolved external symbol
Client.obj : error LNK2001: unresolved external symbol
Client.obj : error LNK2001: unresolved external symbol
Debug/Client.exe : fatal error LNK1120: 9 unresolved externals
执行 link.exe 时出错.
Client.exe - 1 error(s), 0 warning(s)
原因是缺少了WS2_32.LIB,要导入这个lib,有两种方法:
方法一:可以在第二行后回车加下面的语句解决:
#pragma comment(lib,"ws2_32.lib")
方法二:依次单击“工程”——》“增加到工程”——》“文件”,然后在弹出的对话框中找到ws2_32.lib文件所在(C:\Program Files\Microsoft Visual Studio\VC98\Lib)添加ws2_32.lib即可。
阅读(1209) | 评论(0) | 转发(0) |