//一个简单的socket客户端,但是运行总出错,高手帮忙指点一下,3Q!
#include<winsock2.h>
#include<windows.h>
#include<stdio.h>
#include<string.h>
#pragma comment(lib,"Ws2_32")
BOOL varA,varB;
SOCKET ClientSocket = INVALID_SOCKET;
int useage(char *filename)
{
printf("useage:%s serverip serverport\n",filename);
printf("Eg:%s 127.0.0.1 80\n");
return 0;
}
int error(char *string)
{
printf("error on %s\n",string);
exit(0);
}
DWORD WINAPI ThreadFuncA( LPVOID lpParam ) //接收线程
{
char recv_buff[1024];
DWORD nByteToWrite;
varA = 1;
while(true)
{
nByteToWrite = recv(ClientSocket,recv_buff,sizeof(recv_buff),0);
if(nByteToWrite)
printf("%s\n",recv_buff);
}
return 0;
}
DWORD WINAPI ThreadFuncB( LPVOID lpParam ) //发送线程
{
char send_buff[1024];
varB = 1;
while (true)
{
scanf("%s",send_buff);
send(ClientSocket,send_buff,sizeof(send_buff,0),0);
if(strcmp(send_buff,"quit")==0||strcmp(send_buff,"exit")==0)
return 0;
}
return 0;
}
int main(int argc,char **argv)
{
if(argc!=3)
useage(*argv);
WSADATA ws;
struct sockaddr_in server_addr;
if(WSAStartup(MAKEWORD(2,2),&ws)!=0)
error("WSAStartup");
if((ClientSocket=socket(AF_INET,SOCK_STREAM,0))<0)
error("socket");
long server=inet_addr(argv[1]);
unsigned short port=(unsigned short int) atoi(argv[2]);
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr=server;
server_addr.sin_port=htons(port);
DWORD dwThreadIdA,dwThreadIdB;
varA = 0;
varB = 0;
CreateThread(NULL, 0, ThreadFuncA, NULL, 0, &dwThreadIdA);
CreateThread(NULL, 0, ThreadFuncB, NULL, 0, &dwThreadIdB);
Sleep(200);
BOOL Connected=false;
for(;!Connected;)
{
if(connect(ClientSocket,(sockaddr *)&server_addr,sizeof(struct sockaddr))<0)
error("connect");
else
{
printf("connect successful!\n");
Connected=true;
}
}
Sleep(250);
closesocket(ClientSocket);
WSACleanup();
return 0;
}