服务端程序,linux下编译通过
#include
#include
#include
#include
#define MAXLINE 100
#define SA struct sockaddr
#define SOCKET int
using namespace std;
int main()
{
cout << "this is a server!" << endl;
struct sockaddr_in server,client;
SOCKET listen_sock = socket(AF_INET, SOCK_STREAM, 0); // 创建监听套接字
if(listen_sock < 0)
{
perror("socket error");
return -1;
}
memset((char *)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(8888);
if(bind(listen_sock, (SA *)&server, sizeof(server)) < 0) // 绑定监听端口
{
perror("bind error");
return -1;
}
listen(listen_sock, 5); // 监听 sockfd 一个已绑定未被连接的套接字描述符 backlog 队列
socklen_t n = (socklen_t)sizeof(client);
SOCKET conn_sock = (SOCKET)accept(listen_sock, (SA *)&client, &n); // 创建连接套接字
if(conn_sock < 0)
perror("accept error");
else
{
// 接受client请求信息
unsigned char buf[MAXLINE+1];
memset(buf, 0, sizeof(buf));
if((n = recv(conn_sock, buf, MAXLINE, 0)) < 0)
perror("recv error");
else
{
buf[n] = 0;
cout << "recv from client : " << buf << endl;
}
// 服务器处理业务///
// ////
////////////////////
// 返回服务器处理结果字符串
if(send(conn_sock, "server!", 7, 0) < 0)
perror("send error");
close(conn_sock);
}
close(listen_sock);
return 0;
}
客户端程序
#include
#include
#include
#include
#include
#define MAXLINE 100
#define SA struct sockaddr
#define SOCKET int
using namespace std;
const char *ip = {"127.0.0.1"};
const int port = 8888;
int main()
{
cout << "this is a client!" << endl;
cout << "conn server ip:" << ip << endl;
cout << "conn server port:" << port << endl;
SOCKET sockfd;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{// 创建一个套接字,tcp协议,流套接字,通信协议
perror("socket error");
return -1;
}
struct sockaddr_in servaddr; // 通信地址类型变量
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
struct hostent *hp;
hp = gethostbyname(ip);
memcpy((char*)&servaddr.sin_addr, (char*)hp->h_addr, hp->h_length);
if(connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) < 0) // 建立连接
{
perror("connect error");
return -1;
}
cout << "YOU:" << endl;
string message;
cin >> message;
if(send(sockfd, message.c_str(), message.size(), 0) < 0) // 发送请求字符串
{
perror("send error");
return -1;
}
int n;
char recvline[MAXLINE+1];
while((n = recv(sockfd, recvline, MAXLINE, 0)) > 0) // 接受,阻塞
{
recvline[n] = 0;
cout << "recv from server: "<< recvline <<endl;
}
if(n < 0)
perror("recv error");
close(sockfd); // 关闭套接字连接
return 0;
}