客户端socket程序编写过程:
1、定义socket、地址结构和端口;
SOCKET ClientSocket;
struct sockaddr_in sa;
int ServerPort=5555;
2、加载socket动态链接库
WSAStartup(MAKEWORD(1,1),&WsaData)
3、创建socket,填写服务器的地址
ClientSocket=socket(AF_INET,SOCK_STREAM,0)
unsigned long uladdr=inet_addr("127.0.0.1")
3、初始化服务器地址结构,连接服务器
sa.sin_family=AF_INET;
sa.sin_port=htons(ClientSocket);
sa.sin_addr.S_un.S_addr=uladdr;
connect(ClientSocket,(const sockaddr*)&sa,sizeof(sa))
4、从服务器接受数据;
recv(ClientSocket,buff,sizeof(buff),0);
5、关闭socket并写在socket动态链接库
closesocket(ClientSocket);
WSACleanup();
6、例子,可以和之前的server进行通信
#include <winsock.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(int argc,char*argv[])
{
SOCKET ClientSocket;
struct sockaddr_in sa;
int ServerPort=5555;
char buff[256];
WSADATA WsaData;
unsigned long uladdr;
//uladdr=inet_addr(argv[1]); //用户输入IP
uladdr=inet_addr("127.0.0.1"); //用户输入IP
//servport=atoi(argv[2]); 用户自定义端口
WSAStartup(MAKEWORD(1,1),&WsaData);//Initialize
ClientSocket=socket(AF_INET,SOCK_STREAM,0);// Creat socket
//fill server address struct
memset(&sa,0,sizeof(sa));
sa.sin_family=AF_INET;
sa.sin_port=htons(ClientSocket);
sa.sin_addr.S_un.S_addr=uladdr;
connect(ClientSocket,(const sockaddr*)&sa,sizeof(sa));//connecting
memset(buff,0,sizeof(buff));//receive
recv(ClientSocket,buff,sizeof(buff),0);
cout<<"/nthese the world in buff received"<<endl;
for(int i=0;i<256;i++)
{
cout<<buff[i];
}
cout<<endl;
cout<<"OK!"<<endl;
closesocket(ClientSocket);
WSACleanup();
return 0;
}