设计程序
1.阅读TCP、UDP数据通信的例子8-2、8-7,理解并运行查看其功能。
2. 编写程序,使用socket网络接口函数,实现同一网段的两台主机的聊天。注:使用多线程,实现实时聊天功能。(使用UDP或TCP方式)
Server.cpp
#include <cstring>
#include <locale>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFSIZE 4096
#define SERV_PORT 9528
#include <iostream>using namespace std;void sys_err(const char* str){perror(str);exit(1);
}int main(){// listen fdint lfd = 0;// client fdint cfd = 0;char buf[BUFSIZE];// 创建服务端负责监听的socketlfd = socket(AF_INET, SOCK_STREAM, 0);// 设置服务端socket 地址结构struct sockaddr_in serv_addr;serv_addr.sin_family = AF_INET;// htons host to network short 主机字节序转网络字节序短整形 16位端口号serv_addr.sin_port = htons(SERV_PORT);// htonl host to network long 主机字节序转网络字节序长整形 32位IP地址serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);// 监听socket绑定地址结构if (bind(lfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1)sys_err("bind");// 设置监听上限listen(lfd, 128);// 阻塞监听struct sockaddr_in cli_addr; // 监听到的连接的地址结构的传出参数socklen_t cli_addr_len;cfd = accept(lfd, (struct sockaddr*)&cli_addr, &cli_addr_len);if (cfd == -1)sys_err("accept");// 打印连接信息char client_IP[40]; // IP字符串cout << "client connected..." << endl;printf("client ip : %s\n",inet_ntop(AF_INET, &cli_addr.sin_addr.s_addr, client_IP, sizeof(client_IP)));cout << "client port : " << ntohs(cli_addr.sin_port) << endl;// 处理while (1){// 读取客户端内容int len = read(cfd, buf, sizeof buf);if (len == 0){cout << "client disconnected..." << endl;break;}// 回显接受的客户端内容cout << "received client msg : " << buf << endl;for (int i = 0; i < len; i++)buf[i] = toupper(buf[i]);// 回复客户端write(cfd, buf, len);}close(lfd);close(cfd);return 0;
}
可以使用shell命令测试服务端代码
nc 127.0.0.1 9528
Client.cpp
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
#include <error.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>
#define BUFSIZE 4096
#define SERV_PORT 9528using namespace std;void sys_err(const char *str){perror(str);exit(1);
}int main(){const char *serv_ip = "127.0.0.1"; // 要连接的服务器IP// 设置要连接的服务器的地址结构struct sockaddr_in serv_addr;serv_addr.sin_family = AF_INET;inet_pton(AF_INET, serv_ip, &serv_addr.sin_addr.s_addr);serv_addr.sin_port = htons(SERV_PORT);int cfd = socket(AF_INET, SOCK_STREAM, 0);if(cfd == -1)sys_err("socket");if(connect(cfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1){sys_err("connect");}char buf[BUFSIZE];while(1){cout << "Please input your sent to server msg : ";cin >> buf;write(cfd, buf, strlen(buf));read(cfd, buf, sizeof(buf));cout << "received server msg : " << buf << endl;}}
编译运行
g++ -o server server.cpp
g++ -o client client.cpp