VC Socket 实现服务器和客户端的通讯

时间:2022-12-31 15:38:03

Remark

A.服务器程序和客户端程序都要添加库文件ws2_32.lib   project->setting->link->Object/library modules:最后的地方添加ws2_32.lib,要加空格

B.第一次端口设置6000被占用,改为8000后正常

1.服务器程序的实现如下:

#include <stdio.h>

#include <WINSOCK2.H>

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

//apply for version

wVersionRequested = MAKEWORD(1, 1);

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 ) {

return;

}

//check version

if ( LOBYTE( wsaData.wVersion ) != 1 ||

        HIBYTE( wsaData.wVersion ) != 1 ) {

WSACleanup( );

return;

}

    //declare socket;

SOCKET sockserv = socket(AF_INET,SOCK_STREAM,0);

//declare addr for Serv

SOCKADDR_IN addrServ;

addrServ.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

addrServ.sin_family = AF_INET;

//set port;

addrServ.sin_port = htons(8000);

//binding  ip;

    if(bind(sockserv,(SOCKADDR*)&addrServ,sizeof(SOCKADDR)))

{

printf("%s","binding error");

return;

}

// can listen for 5 clients PC

if (listen(sockserv,5))

{

printf("%s","listengiing error");

return;

}

//declare  addr for Client

SOCKADDR_IN addrClient;

int len = sizeof(SOCKADDR);

while(1)

{

//waitting client send data

SOCKET sockConn = accept(sockserv,(SOCKADDR*)&addrClient,&len);

char sendBuf[100];

sprintf(sendBuf,"Welcome %s :\n",inet_ntoa(addrClient.sin_addr));

//send data to client

send(sockConn,sendBuf,sizeof(sendBuf)+1,0);

char recvBuf[100] = {0};

recv(sockConn,recvBuf,sizeof(recvBuf)+1,0);

printf("%s",recvBuf);

closesocket(sockConn);

}

2.客户端的程序:

#include <stdio.h>

#include <WINSOCK2.H>

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

//apply for version

wVersionRequested = MAKEWORD(1, 1);

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 ) {

return;

}

//check version

if ( LOBYTE( wsaData.wVersion ) != 1 ||

        HIBYTE( wsaData.wVersion ) != 1 ) {

WSACleanup( );

return;

}

    //declare socket;

SOCKET sockserv = socket(AF_INET,SOCK_STREAM,0);

//declare addr for Serv

SOCKADDR_IN addrServ;

addrServ.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

addrServ.sin_family = AF_INET;

//set port;

addrServ.sin_port = htons(8000);

//binding  ip;

    if(bind(sockserv,(SOCKADDR*)&addrServ,sizeof(SOCKADDR)))

{

printf("%s","binding error");

return;

}

// can listen for 5 clients PC

if (listen(sockserv,5))

{

printf("%s","listengiing error");

return;

}

//declare  addr for Client

SOCKADDR_IN addrClient;

int len = sizeof(SOCKADDR);

while(1)

{

//waitting client send data

SOCKET sockConn = accept(sockserv,(SOCKADDR*)&addrClient,&len);

char sendBuf[100];

sprintf(sendBuf,"Welcome %s :\n",inet_ntoa(addrClient.sin_addr));

//send data to client

send(sockConn,sendBuf,sizeof(sendBuf)+1,0);

char recvBuf[100] = {0};

recv(sockConn,recvBuf,sizeof(recvBuf)+1,0);

printf("%s",recvBuf);

closesocket(sockConn);

}

}