服务器端:
#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 a space for the received data
int recv_resu

本文介绍了使用C++进行Socket编程的基本步骤,包括创建服务器端和客户端的实现过程。服务器端涉及监听、接受连接请求,客户端则涉及连接服务器并发送数据。通过实例详细解析了Socket通信的关键代码和流程。
最低0.47元/天 解锁文章
3万+

被折叠的 条评论
为什么被折叠?



