C-socket程式設計-多程序版併發伺服器
阿新 • • 發佈:2019-01-05
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "wrap.h"
int main()
{
//建立套接字
int serv_sock = Socket(AF_INET,SOCK_STREAM,0);
//將套接字與IP,PORT繫結
//建立sokaddr_in結構體,並經行本地位元組序和網路位元組序的轉換
struct sockaddr_in serv_addr;
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr=Inet_addr("127.0.0.1");
serv_addr.sin_port = Htons(1234);
Bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
//進入監聽狀態,等待使用者發起請求
listen(serv_sock,20);
//接收客戶端請求
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size =sizeof(clnt_addr);
int clnt_sock;
int pid;
while((clnt_sock=Accept(serv_sock,(struct sockaddr *)&clnt_addr,&clnt_addr_size)) !=0)
{
pid=fork();
if (pid==-1)
{
perror("fork err");
exit(1);
}
if(pid==0)
{
char buf[4096];
int n,i;
while((n=read(clnt_sock,buf,sizeof(buf))) != 0)
{
for(i=0;i<n;i++)
{
buf[i]=toupper(buf[i]);
}
write(clnt_sock,buf,n);
}
//關閉套接字
close(clnt_sock);
exit(2);
}
else
{
//關閉套接字
close(clnt_sock);
}
}
close(serv_sock);
return 0;
}
第二個例子
/* For sockaddr_in */
#include <netinet/in.h>
/* For socket functions */
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE 16384
char
rot13_char(char c)
{
/* We don't want to use isalpha here; setting the locale would change
* which characters are considered alphabetical. */
if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M'))
return c + 13;
else if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z'))
return c - 13;
else
return c;
}
void
child(int fd)
{
char outbuf[MAX_LINE+1];
size_t outbuf_used = 0;
ssize_t result;
while (1) {
char ch;
result = recv(fd, &ch, 1, 0);
if (result == 0) {
break;
} else if (result == -1) {
perror("read");
break;
}
/* We do this test to keep the user from overflowing the buffer. */
if (outbuf_used < sizeof(outbuf)) {
outbuf[outbuf_used++] = rot13_char(ch);
}
if (ch == '\n') {
send(fd, outbuf, outbuf_used, 0);
outbuf_used = 0;
continue;
}
}
}
void
run(void)
{
int listener;
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = 0;
sin.sin_port = htons(40713);
listener = socket(AF_INET, SOCK_STREAM, 0);
#ifndef WIN32
{
int one = 1;
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
}
#endif
if (bind(listener, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
perror("bind");
return;
}
if (listen(listener, 16)<0) {
perror("listen");
return;
}
while (1) {
struct sockaddr_storage ss;
socklen_t slen = sizeof(ss);
int fd = accept(listener, (struct sockaddr*)&ss, &slen);
if (fd < 0) {
perror("accept");
} else {
if (fork() == 0) {
child(fd);
exit(0);
}
}
}
}
int
main(int c, char **v)
{
run();
return 0;
}