用c++编写一次启动Server端和Client端后,首先由Server端发‘1’给Client端,Client端将接收到的数据加1后,发该数据给Server端,Server端再将数据加1后发给Client端,依次类推。直到Server端收到数据20,Client收到19时,两方中断收发。
时间: 2024-03-25 07:35:38 浏览: 52
C++写的客户端与服务端
这是一个简单的Socket编程实例,使用TCP协议实现。以下是Server端的代码:
```c++
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<unistd.h>
#define BUF_SIZE 1024
using namespace std;
void error_handling(const char* message);
int main(int argc, char* argv[]){
int serv_sock, clnt_sock;
char message[BUF_SIZE];
int str_len, i;
struct sockaddr_in serv_addr, clnt_addr;
socklen_t clnt_addr_size;
if(argc!=2){
cout<<"Usage : "<<argv[0]<<" <port>\n";
exit(1);
}
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock==-1)
error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1)
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
clnt_addr_size=sizeof(clnt_addr);
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_addr, &clnt_addr_size);
if(clnt_sock==-1)
error_handling("accept() error");
int data = 1;
while(data < 21){
write(clnt_sock, &data, sizeof(data)); // send data to client
read(clnt_sock, &data, sizeof(data)); // receive data from client
cout<<"Server received data: "<<data<<endl;
data++;
}
close(clnt_sock);
close(serv_sock);
return 0;
}
void error_handling(const char* message){
cerr<<message<<endl;
exit(1);
}
```
以下是Client端的代码:
```c++
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<unistd.h>
#define BUF_SIZE 1024
using namespace std;
void error_handling(const char* message);
int main(int argc, char* argv[]){
int sock;
char message[BUF_SIZE];
int str_len;
int data = 0;
struct sockaddr_in serv_addr;
if(argc!=3){
cout<<"Usage : "<<argv[0]<<" <IP> <port>\n";
exit(1);
}
sock=socket(PF_INET, SOCK_STREAM, 0);
if(sock==-1)
error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(argv[1]);
serv_addr.sin_port=htons(atoi(argv[2]));
if(connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1)
error_handling("connect() error");
while(data < 20){
read(sock, &data, sizeof(data)); // receive data from server
cout<<"Client received data: "<<data<<endl;
data++;
write(sock, &data, sizeof(data)); // send data to server
}
close(sock);
return 0;
}
void error_handling(const char* message){
cerr<<message<<endl;
exit(1);
}
```
阅读全文