socket网络编程入门写hello world

1、服务器端

#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>

using namespace std;

void error_handling(const char* message);

int main(int argc, char **argv)
{
	if (argc != 2)
	{
		cout << "Usage: " << argv[0] << " <port>" << endl;
		exit(1);
	}

	int server_socket = socket(PF_INET, SOCK_STREAM, 0);    //获得服务器socket资源
	if (server_socket == -1)
	{
		error_handling("socket() error");
	}

	struct sockaddr_in server_addr;
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	server_addr.sin_port = htons(atoi(argv[1]));

	if (bind(server_socket, (const struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)   // 为socket分配ip和端口号
	{
		error_handling("bind() error");
	}

	if (listen(server_socket, 5) == -1)  // 将socket置为可连接状态
	{
		error_handling("listen() error");
	}

	while (true)
	{
		struct sockaddr_in client_addr;
		socklen_t client_addr_size = sizeof(client_addr);
		int client_socket = accept(server_socket, (struct sockaddr*)(&client_addr), &client_addr_size);   // 受理连接请求
		if (client_socket == -1)
		{
			error_handling("accept() error");
		}

		const string message{"Hello World!"};
		write(client_socket, message.data(), message.size());  //传输数据给客户端

		close(client_socket);   //关闭客户端socket资源
	}

	close(server_socket);  //关闭服务器端socket资源

	return 0;
}

void error_handling(const char* message)
{
	cout << message << endl;
	exit(1);
}

2、客户端实现

#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstdlib>

using namespace std;

void error_handling(const char* message);

int main(int argc, char **argv)
{
	if (argc != 3)
	{
		cout << "Usage: " << argv[0] << " <IP> <port>" << endl;
		exit(1);
	}

	int client_socket = socket(PF_INET, SOCK_STREAM, 0);  //创建客户端socket资源
	if (client_socket == -1)
	{
		error_handling("socket() error");
		exit(1);
	}

    // 设置要连接的服务器地址
	struct sockaddr_in server_addr;
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);
	server_addr.sin_port = htons(atoi(argv[2]));

	if (connect(client_socket, (const struct sockaddr*)&server_addr, sizeof(server_addr)) == -1)  //连接服务器
	{
		error_handling("connect() error");
		exit(1);
	}

	char message[30];
	int msg_size = read(client_socket, message, sizeof(message) - 1); //向服务器发送请求
	if (msg_size == -1)
	{
		error_handling("read() error");
		exit(1);
	}

	cout << "Message from server: " << message << endl;

	close(client_socket);  //关闭socket

	return 0;
}

void error_handling(const char* message)
{
	cout << message << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值