C语言socket编程——linux环境

先写一个服务器端的监听程序,功能室从客户端读取字符,接收到后告知客户端“I got your message: ”+收到的消息:server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> #define MAXLINE 1000
#define SERV_PORT 9931 void doprocessing(int sock, struct sockaddr_in cliaddr)
{
int n; char str[INET_ADDRSTRLEN];
char *buf = (char *)malloc(MAXLINE);
char *reply = (char *)malloc(MAXLINE*2);
memset(buf, '\0', MAXLINE);
while (1) {
n = read(sock, buf, MAXLINE);
strcpy(reply,"I got your message: ");
if (n < 0) {
perror("Error reading from socket!");
return;
} else {
printf("Connect from %s:%d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, str, sizeof(str)), ntohs(cliaddr.sin_port));
strcat(reply,buf);
printf("receive %s\n",buf);
write(sock, reply, MAXLINE);
}
memset(buf,0,sizeof(char)*MAXLINE);
memset(reply,0,sizeof(char)*MAXLINE);
}
free(reply);
free(buf);
} int main(void)
{
struct sockaddr_in servaddr, cliaddr; int listenfd, connfd, pid;
socklen_t cliaddr_len = sizeof(cliaddr); listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd < 0) {
perror("Error opening socket!");
exit(-1);
} memset(&servaddr, 0, sizeof(struct sockaddr_in));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("10.13.81.182");
servaddr.sin_port = htons(SERV_PORT); bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); listen(listenfd, 2000); printf("server服务器开始等待客户端连接 ...\n"); while (1) {
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len); pid = fork(); if (pid == -1) {
perror("call to fork");
exit(-1);
} else if (pid == 0) {
close(listenfd);
doprocessing(connfd, cliaddr);
exit(0);
} else {
close(connfd);
}
} return 0;
}

再写一个客户端通过socket通信向服务器发送数据的代码:cli.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> #define MAXLINE 1000
#define SERV_PORT 9931 int main(int argc, char *argv[])
{ struct sockaddr_in servaddr;
char *buf = (char *)malloc(MAXLINE);
char *rec = (char *)malloc(MAXLINE);
int servfd, n; servfd = socket(AF_INET, SOCK_STREAM, 0); memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("10.13.81.182");
servaddr.sin_port = htons(SERV_PORT); connect(servfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
while (fgets(buf, MAXLINE, stdin)!= NULL) {
write(servfd, buf, strlen(buf)); n = read(servfd, rec, MAXLINE);
if (n == 0) {
perror("The other side has been closed.");
exit(-1);
} else {
printf("从服务器返回的信息为:%s\n", rec);
}
memset(rec,0,sizeof(char)*MAXLINE);
memset(buf,0,sizeof(char)*MAXLINE);
}
close(servfd);
return 0;
}

关于TCP连接的稍后补上

上一篇:freemarker是什么东西?


下一篇:加载gif图片的方法:(需要SDWebImage方法)