admin 管理员组

文章数量: 887032


2023年12月22日发(作者:stream的reduce方法)

C语言实现Socket编程

tcpsrv.c的内容如下:

#include

#include

#define RECEIVE_MAX_LENGTH 100

#define SEND_MAX_LENGTH 100

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 )

{

return;

}

if ( LOBYTE( on ) != 1

|| HIBYTE( on ) != 1 )

{

WSACleanup( );

return;

}

SOCKET socksrv = socket(AF_INET,SOCK_STREAM,0);//监听的套接字

SOCKADDR_IN socketadd;

_addr.S_un.S_addr = htonl(INADDR_ANY);

_family = AF_INET;

_port = htons(7001);

if( SOCKET_ERROR == bind(socksrv,(SOCKADDR*)&socketadd,sizeof(SOCKADDR)) )

{

printf("bind errn");

return;

}

if( SOCKET_ERROR == listen(socksrv,5) )

{

printf("listen err");

return;

}

SOCKADDR_IN sockclient;

int len = sizeof(SOCKADDR);

while(1)

{

SOCKET sockconn = accept(socksrv,(SOCKADDR*)&sockclient,&len);//建立连接的套节字

if(INVALID_SOCKET == sockconn )

{

printf("acc errn");

return;

}

char sendData[SEND_MAX_LENGTH];

//scanf("%s",sendData);

//strcpy(sendData, "hello client, i'm server");

sprintf(sendData,"%s","hello client, i'm server");

if( SOCKET_ERROR == send(sockconn,sendData,strlen(sendData)+1,0) )

{

printf("send errn");

return;

}

char getData[RECEIVE_MAX_LENGTH];

recv(sockconn,getData,RECEIVE_MAX_LENGTH,0);

printf("%sn",getData);

closesocket(sockconn);

}

}

tcpclient.c 的内容如下:

#include

#include

#define RECEIVE_MAX_LENGTH 100

#define SEND_MAX_LENGTH 100

void main()

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 )

{

return;

}

if ( LOBYTE( on ) != 1

|| HIBYTE( on ) != 1 )

{

WSACleanup( );

return;

}

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

SOCKADDR_IN clientadd;

_addr.S_un.S_addr = inet_addr("127.0.0.1");

_family = AF_INET;

_port = htons(7001);

if( SOCKET_ERROR == connect(socketClient,(SOCKADDR*)&clientadd,sizeof(SOCKADDR)) )

{

printf("con errn");

return;

}

char getData[RECEIVE_MAX_LENGTH];

if(recv(socketClient,getData,RECEIVE_MAX_LENGTH,0) == SOCKET_ERROR)

{

printf("recv errn");

return;

}

else

{

printf("%sn",getData);

}

char sendData[SEND_MAX_LENGTH];

//scanf("%s",sendData);

strcpy(sendData, "hello server, i'm client");

//sprintf(sendData,"%s","hello server, i'm client");

send(socketClient,sendData,sizeof(sendData)+1,0);

closesocket(socketClient);

WSACleanup();

}

必须先运行服务端程序,再运行客户端程序!


本文标签: 运行 程序 编程 连接