答:可以正常工作。
测试代码:
client:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<iostream>
using namespace std;
#define MAXLINE 4096
int main(int argc, char** argv) {
int sockfd, n;
char recvline[4096], sendline[4096];
struct sockaddr_in servaddr;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
return 0;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(6666);
if (inet_pton(AF_INET, "10.221.68.42", &servaddr.sin_addr) <= 0) {
printf("inet_pton error for %s\n", argv[1]);
return 0;
}
if (connect(sockfd, (struct sockaddr*) & servaddr, sizeof(servaddr)) < 0) {
printf("connect error: %s(errno: %d)\n", strerror(errno), errno);
return 0;
}
char buf[1024] = { 0 };
while (1) {
send(sockfd, "my name is client", strlen("my name is client"), 0);
memset(buf, 0, 1024);
recv(sockfd, buf, 1000, 0);
cout << buf << endl;
sleep(2);
}
close(sockfd);
return 0;
}
server
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<unistd.h>
#include <pthread.h>
#include<iostream>
using namespace std;
#define MAXLINE 4096
void* worker(void* arg) {
int connfd = *((int*)arg);
char buf[1024] = { 0 };
while (1) {
memset(buf, 0, 1024);
int ret = recv(connfd, buf, 1000, 0);
if (ret <= 0) {
return nullptr;
}
cout << buf << endl;
send(connfd, "hello world", 12, 0);
}
}
int main(int argc, char** argv) {
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[4096];
int n;
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
printf("create socket error: %s(errno: %d)\n", strerror(errno), errno);
return 0;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(6666);
if (bind(listenfd, (struct sockaddr*) & servaddr, sizeof(servaddr)) == -1) {
printf("bind socket error: %s(errno: %d)\n", strerror(errno), errno);
return 0;
}
if (listen(listenfd, 10) == -1) {
printf("listen socket error: %s(errno: %d)\n", strerror(errno), errno);
return 0;
}
printf("======waiting for client's request======\n");
int count = 0;
while (1) {
if (count >= 3) {
close(listenfd);
sleep(1000000);
}
if ((connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1) {
printf("accept socket error: %s(errno: %d)", strerror(errno), errno);
continue;
}
pthread_t pt;
int* conn = new int(connfd);
pthread_create(&pt, nullptr, worker, conn);
pthread_detach(pt);
count++;
}
close(listenfd);
return 0;
}