Socket套接字程式編寫步驟
分別建兩個工程。。把cpp拷貝進去執行就可以了。。。
server端:
#include <WINSOCK2.H>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
void main()
{
//建立套接字
WORD myVersionRequest;
WSADATA wsaData;
myVersionRequest=MAKEWORD(1,1);
int err;
err=WSAStartup(myVersionRequest,&wsaData);
if (!err)
{
printf("已開啟套接字\n");
}
else
{
//進一步繫結套接字
printf("巢狀字未開啟!");
return;
}
SOCKET serSocket=socket(AF_INET,SOCK_STREAM,0);//建立了可識別套接字
//需要繫結的引數
SOCKADDR_IN addr;
addr.sin_family=AF_INET;
addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//ip地址
addr.sin_port=htons(6000);//繫結埠
bind(serSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR));//繫結完成
listen(serSocket,5);//其中第二個引數代表能夠接收的最多的連線數
//////////////////////////////////////////////////////////////////////////
//開始進行監聽
//////////////////////////////////////////////////////////////////////////
SOCKADDR_IN clientsocket;
int len=sizeof(SOCKADDR);
while (1)
{
SOCKET serConn=accept(serSocket,(SOCKADDR*)&clientsocket,&len);//如果這裡不是accept而是conection的話。。就會不斷的監聽
char sendBuf[100];
sprintf(sendBuf,"welcome %s to bejing",inet_ntoa(clientsocket.sin_addr));//找對對應的IP並且將這行字列印到那裡
send(serConn,sendBuf,strlen(sendBuf)+1,0);
char receiveBuf[100];//接收
recv(serConn,receiveBuf,strlen(receiveBuf)+1,0);
printf("%s\n",receiveBuf);
closesocket(serConn);//關閉
WSACleanup();//釋放資源的操作
}
}
client端:
#include <WINSOCK2.H>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
void main()
{
int err;
WORD versionRequired;
WSADATA wsaData;
versionRequired=MAKEWORD(1,1);
err=WSAStartup(versionRequired,&wsaData);//協議庫的版本資訊
if (!err)
{
printf("客戶端巢狀字已經開啟!\n");
}
else
{
printf("客戶端的巢狀字開啟失敗!\n");
return;//結束
}
SOCKET clientSocket=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN clientsock_in;
clientsock_in.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
clientsock_in.sin_family=AF_INET;
clientsock_in.sin_port=htons(6000);
//bind(clientSocket,(SOCKADDR*)&clientsock_in,strlen(SOCKADDR));//注意第三個引數
//listen(clientSocket,5);
connect(clientSocket,(SOCKADDR*)&clientsock_in,sizeof(SOCKADDR));//開始連線
char receiveBuf[100];
recv(clientSocket,receiveBuf,101,0);
printf("%s\n",receiveBuf);
send(clientSocket,"hello,this is client",strlen("hello,this is client")+1,0);
closesocket(clientSocket);
WSACleanup();
}