|
楼主 |
发表于 2014-9-24 20:12:49
|
显示全部楼层
18、网络编程
TCP-》面向连接 UDP-》不面向连接
可靠 不可靠
(传文件、准确数据)
客户端(主动发请求) 服务器(被动反应)
TCP客户端流程:
iSocketClient = Socket(AF_INET,SOCK_STREAM,0);
创建socket句柄 参数1 表示用ipv4
iRet = connect(iSocketClient, (const struct sockaddr *)&tSocketServerAddr, sizeof(struct sockaddr));
if (-1 == iRet)
{
printf("connect error!\n");
return -1;
}
与服务器连接
tSocketServerAddr结构体
可以开始传数据(发数据:write/send ,接受数据:read/recv)
fgets(ucSendBuf, 999, stdin) 获取用户输入的数据
send(iSocketClient, ucSendBuf, strlen(ucSendBuf), 0); 第二个参数:要发的数据
TCP服务器端流程:
iSocketServer = socket(AF_INET, SOCK_STREAM, 0);
创建socket句柄 判断它的返回值
iRet = bind(iSocketServer, (const struct sockaddr *)&tSocketServerAddr, sizeof(struct sockaddr));
绑定端口号、ip地址
tSocketServerAddr结构体
tSocketServerAddr.sin_family = AF_INET; //TCP
tSocketServerAddr.sin_port = htons(SERVER_PORT);
tSocketServerAddr.sin_addr.s_addr = INADDR_ANY;
memset(tSocketServerAddr.sin_zero, 0, 8);
开始监听
iRet = listen(iSocketServer, BACKLOG);
#define BACKLOG 10
表示可以有10个客户端跟服务器连接
iSocketClient = accept(iSocketServer, (struct sockaddr *)&tSocketClientAddr, &iAddrLen);
等待客户端来连接 (没有客户端连接,此处会阻塞)
tSocketClientAddr存放客户端信息
iRecvLen = recv(iSocketClient, ucRecvBuf, 999, 0);
接收数据 ucRecvBuf 存放接收到的数据
UDP服务端流程:
创建socket句柄
iSocketServer = socket(AF_INET, SOCK_DGRAM, 0);
绑定服务器的ip和端口:
iRet = bind(iSocketServer, (const struct sockaddr *)&tSocketServerAddr, sizeof(struct sockaddr));
接收数据:
iRecvLen = recvfrom(iSocketServer, ucRecvBuf, 999, 0, (struct sockaddr *)&tSocketClientAddr, &iAddrLen);
第二个参数是存放接收到的数据,第三个参数是接收的字节数
UDP客户端流程:
创建socket句柄
iSocketClient = socket(AF_INET, SOCK_DGRAM, 0);
收发数据:
iSendLen = sendto(iSocketClient, ucSendBuf, strlen(ucSendBuf), 0, (const struct sockaddr *)&tSocketServerAddr, iAddrLen);
参数五告诉客户端要发的服务器 |
|