Linux下基于C++的TCP连接demo代码分享(C++,Linux,Socket)

#C++实现TCP连接

@(C++代码)[网络编程, tcp, C++, C++实现]

server.cpp:

#include

#include

#include

#include

#include

#include

#include

#define PORT 8888

void process_conn_client(int s)

{

ssize_t size = 0;

char buffer[1024];

while(1)

{

size = read(0, buffer, 1024);

if(size > 0)

{

write(s, buffer, size);

size = read(s, buffer, 1024);

write(1, buffer, size);

}

}

}

int main(int argc,char *argv[])

{

int s;

struct sockaddr_in server_addr;

s = socket(AF_INET, SOCK_STREAM, 0);

if(s < 0)

{

printf("socket error\n");

return -1;

}

bzero(&server_addr,sizeof(server_addr));

server_addr.sin_family = AF_INET;

server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

server_addr.sin_port = htons(PORT);

inet_pton(AF_INET, argv[1], &server_addr.sin_addr);

connect(s, (struct sockaddr*)&server_addr, sizeof(struct sockaddr));

process_conn_client(s);

close(s);

return 0;

}


client:

#include

#include

#include

#include

#include

#include

#include

#define PORT 8888

#define BACKLOG 2

void process_conn_server(int s)

{

ssize_t size = 0;

char buffer[1024];

while(1)

{

size = read(s, buffer,1024);

if(size == 0) return;

sprintf(buffer, "%d bytes altogether\n",size);

write(s, buffer, strlen(buffer)+1);

}

}

int main()

{

int ss,sc; //socket server,socket client

struct sockaddr_in server_addr;

struct sockaddr_in client_addr;

int err;

pid_t pid;

//create AF_INET socket

ss = socket(AF_INET, SOCK_STREAM, 0);

if(ss<0)

{

printf("socket error\n");

return -1;

}

//set server address

bzero(&server_addr,sizeof(server_addr));

server_addr.sin_family = AF_INET;

server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

server_addr.sin_port = htons(PORT);

err = bind(ss, (struct sockaddr*)&server_addr , sizeof(server_addr) );

if(err < 0)

{

printf("bind error\n");

return -1;

}

err = listen(ss,BACKLOG);

if(err < 0)

{

printf("listen error\n");

return -1;

}

while(1)

{

socklen_t addrlen = sizeof(struct sockaddr);

sc = accept(ss, (struct sockaddr*)&client_addr, &addrlen);

if(sc < 0)

{

continue;

}

pid = fork();

if(pid == 0)

{

close(ss);

process_conn_server(sc);

}

else

{

close(sc);

}

}

}


makefile:

all:client server

client:tcp_client.o

gcc -o client tcp_client.o

server:tcp_server.o

gcc -o server tcp_server.o

clean:

rm -f client server *.o

免费C/C++基础丶进阶资料,还有实践课程免费领,加群728483370

你可能感兴趣的:(Linux下基于C++的TCP连接demo代码分享(C++,Linux,Socket))