Code 詩亼-邓晓华

努力不一定成功,成功一定要努力,天道酬勤!
  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

基于TCP的网络应用程序的编写

Posted on 2011-02-12 23:33  Code 詩亼  阅读(764)  评论(5编辑  收藏  举报

服务器端Code:

// TcpSrv.cpp
// dxh1688@gmail.com

#include
<Winsock2.h>
#include
<stdio.h>

void main()
{
//加载套接字库(该部分代码可重用,直接复制即可。)
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested
= MAKEWORD(1, 1);
err
= WSAStartup(wVersionRequested, &wsaData);
if (0 != err) {
return;
}
if (1 != LOBYTE(wsaData.wVersion) ||
1 != HIBYTE(wsaData.wVersion)) {
WSACleanup();
return;
}

//创建用于监听的套接字
SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0);

//绑定套接字
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr
= htonl(INADDR_ANY); //将主机字节顺序转换为网络字节顺序后再赋值
addrSrv.sin_family = AF_INET;
addrSrv.sin_port
= htons(6000); //将主机字节顺序转换为网络字节顺序后再赋值
bind(sockSrv, (SOCKADDR *)&addrSrv, sizeof(SOCKADDR));

//将套接字设为监听模式,准备接收客户请求
listen(sockSrv, 5);

SOCKADDR_IN addrClient;
//用来接收客户端的地址信息
int len = sizeof(SOCKADDR);
while (1) {
//等待客户请求的到来
SOCKET sockConn = accept(sockSrv, (SOCKADDR *)&addrClient, &len); //sockConn保存当前客户端与服务器的连接
char sendBuf[100];
sprintf(sendBuf,
"Welcome %s to http://www.sunxin.org",
inet_ntoa(addrClient.sin_addr));
//将in_addr结构体类型地址转换为点分十进制的IP地址

//发送数据
send(sockConn, sendBuf, strlen(sendBuf) +1, 0);

//接收数据
char recvBuf[100];
recv(sockConn, recvBuf,
100, 0);

//打印接收的数据
printf("%s\n", recvBuf);

//关闭套接字
closesocket(sockConn);
}
}

客户端Code:
// TcpClient.cpp
// dxh1688@gmail.com

#include
<Winsock2.h>
#include
<stdio.h>

void main()
{
//加载套接字
WORD wVersionRequestSted;
WSADATA wsaData;
int err;

wVersionRequestSted
= MAKEWORD(1, 1);
err
= WSAStartup(wVersionRequestSted, &wsaData);
if (0 != err) {
return;
}
if (1 != LOBYTE(wsaData.wVersion) ||
1 != HIBYTE(wsaData.wVersion)) {
WSACleanup();
return;
}

//创建套接字
SOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);

//向服务器发出连接请求
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr
= inet_addr("127.0.01"); //将点分十进制表示的IP地址转换为u_long类型后再赋值
addrSrv.sin_family = AF_INET;
addrSrv.sin_port
= htons(6000);
connect(sockClient, (SOCKADDR
*)&addrSrv, sizeof(SOCKADDR));

//接收数据
char recvBuf[100];
recv(sockClient, recvBuf,
100, 0);
printf(
"%s\n", recvBuf);

//发送数据
send(sockClient, "This is Li Si !", strlen("This is Li Si !") + 1, 0);

//关闭套接字
closesocket(sockClient);
WSACleanup();
getchar();
}