windows socket 基本知識 client socket

客戶端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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章