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();
}
必须先运行服务端程序,再运行客户端程序!
版权声明:本文标题:C语言实现Socket编程 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1703198617h441941.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论