winsock 程式設計例

2021-06-17 01:10:54 字數 1980 閱讀 5401

server.cpp

#include

#include

#pragma comment(lib,"ws2_32")

#define port 1234//使用的埠號

#define max_link 10//最大連線數

void main()

printf("socket\n");

//設定伺服器位址結構體

server_addr.sin_family = af_inet;

server_addr.sin_port = htons(port);

server_addr.sin_addr.s_un.s_addr = inaddr_any;

//繫結

if(bind(sockfd,(struct sockaddr*)&server_addr,sizeof(struct sockaddr)) == -1)

printf("bind\n");

//監聽

if(listen(sockfd,max_link) == socket_error)

printf("listen\n");

//生成收發套接字

if((new_fd = accept(sockfd,(struct sockaddr*)&client_addr,&sin_size)) == invalid_socket)

printf("收到請求\n");

printf("客戶端ip:%s\n",inet_ntoa(client_addr.sin_addr));

printf("客戶端port:%d\n",ntohs(client_addr.sin_port));

//接收

//getchar();

num = 0;

while(1)

num = 0;

}closesocket(sockfd);

closesocket(new_fd);

return;

}

/

client.cpp

#include

#include

#pragma comment(lib,"ws2_32")

#define port 1234

int main(int argc, char *argv)

printf("argc is right\n");

wsastartup(makeword(2,2),&ws);

//生成套接字

if((sockfd = socket(af_inet,sock_stream,0)) == invalid_socket)

printf("socket\n");

//設定套接字

server_addr.sin_family = af_inet;

server_addr.sin_port = htons(port);

server_addr.sin_addr.s_un.s_addr = inet_addr(argv[1]);

//連線

if(connect(sockfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr)) == socket_error)

printf("connect\n");

//傳送訊息

buffer[0] = '\0';

while(strcmp(buffer,"end"))

closesocket(sockfd);

return 0;

}

winsock程式設計

伺服器端 include include pragma comment lib,ws2 32.lib using namespace std void do service socket conn while 1 不斷接收客戶端傳送的資料 if lobyte wsadata.wversion 2 h...

Winsock程式設計框架

microsoft的windows sockets api是windows下的網路應用程式介面,為了適用於 windows下的訊息機制和非同步的i o選擇操作,windows sockets api在功能上擴充了將近 20個函式,其中擴充的部分均冠以字首wsa windows sockets asy...

winsock程式設計(一)

一 windows sockets 背景知識 socket的定義。socket控制代碼型別的描述。socket的應用領域。windowssockets規範為windows定義了一套面向位元組相容的網路程式設計介面。windowssockets基於unix socket 伯克利軟體發行機構,bsd,r...