C++ socket编程实例

本文介绍了使用C++进行Socket编程的基本步骤,包括创建服务器端和客户端的实现过程。服务器端涉及监听、接受连接请求,客户端则涉及连接服务器并发送数据。通过实例详细解析了Socket通信的关键代码和流程。
摘要由CSDN通过智能技术生成

服务器端:

#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <iostream>
#include <arpa/inet.h>
#include <unistd.h>

using namespace std;

typedef unsigned char uchar;

int main()
{
	//build the socket for server
	int s = socket(AF_INET, SOCK_STREAM, 0);
	//bind the socket to address
	struct sockaddr_in adr_s;
	adr_s.sin_family = AF_INET;
	adr_s.sin_addr.s_addr = inet_addr("127.0.0.1");
	adr_s.sin_port =htons(1235);
	bind(s, (struct sockaddr *)&adr_s, sizeof(adr_s));
	//listen
	listen(s, 20);
	//accept the request from client
	//build the socket for client, system can bind local address to it automatically
	struct sockaddr_in adr_c;
	socklen_t c_size = sizeof(struct sockaddr_in);
	int c=  accept(s, (struct sockaddr *)&adr_c, &c_size);

	/*
	char str[] = "Hello World!";  // apply for
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值