服务器端的代码实现:
server.cpp:
#include <bits/stdc++.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;
void error_handing(char *message);
void draw(char *s, int n);
const int BUF_SIZE = 1024;
const int SIZE = 4;
int main(int argc, char *argv[])
{
int serv_sock, clnt_sock;
char opinfo[BUF_SIZE];
struct sockaddr_in serv_adr, clnt_adr;
socklen_t clnt_adr_sz;
if (argc != 2)
{
cout << "Usage : " << argv[0] << " <port>" << endl;
exit(1);
}
serv_sock = socket(PF_INET, SOCK_STREAM, 0); //创建套接字服务
if (serv_sock == -1)
{
error_handing("sock() error");
}
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_adr.sin_port = htons(atoi(argv[1]));
if (bind(serv_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) == -1) //设置ip地址端口号
{
error_handing("bind() error");
}
if (listen(serv_sock, 5) == -1) //监听客户端是否有信息传来
{
error_handing("listen() error");
}
clnt_adr_sz = sizeof(clnt_adr);
for (int i = 0; i < 5; i++)
{
clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_adr, &clnt_adr_sz);
int s;
read(clnt_sock, &s, SIZE);
draw(opinfo, s);
write(clnt_sock, opinfo, sizeof(opinfo));
close(clnt_sock);
}
close(serv_sock);
return 0;
}
void error_handing(char *message)
{
cout << message << endl;
exit(1);
}
void draw(char *s, int n)
{
int ct = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (abs(i - n / 2) + abs(j - n / 2) > n / 2)
{
s[ct++] = ' ';
}
else
{
s[ct++] = '*';
}
}
s[ct++] = '\n';
}
s[ct] = '\0';
}
客户端的代码实现:
client.cpp:
#include <bits/stdc++.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;
void error_handing(char *message);
const int BUF_SIZE = 1024;
const int SIZE = 4;
int main(int argc, char *argv[])
{
char info[BUF_SIZE];
int clnt_sock;
struct sockaddr_in serv_adr;
if (argc != 3)
{
cout << "Usage : " << argv[0] << " <port>" << endl;
exit(1);
}
clnt_sock = socket(PF_INET, SOCK_STREAM, 0); //创建套接字服务
if (clnt_sock == -1)
{
error_handing("sock() error");
}
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = inet_addr(argv[1]);
serv_adr.sin_port = htons(atoi(argv[2]));
if (connect(clnt_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) == -1) //设置ip地址端口号
{
error_handing("bind() error");
}
cout << "Operator :";
int a[SIZE];
cin >> a[0];
write(clnt_sock, a, SIZE);
int r_len = 0;
while (r_len <= 500)
{
int t_len = read(clnt_sock, &info[r_len], BUF_SIZE - 1);
r_len += t_len;
}
cout << info << endl;
close(clnt_sock);
return 0;
}
void error_handing(char *message)
{
cout << message << endl;
exit(1);
}
实现效果