伺服器端:
#include #include #include #include #include #include #include #include #define port 1234
#define maxsize 1024
static int clientprocess(int connfd, struct sockaddr_in clientsock)
clientname[strlen(clientname)-1] = '\0';
printf("you got's a connection from %s, client name is %s\n",
inet_ntoa(clientsock.sin_addr), clientname);
while (1)
recvbuf[strlen(recvbuf)-1] = '\0';
printf("received client (%s) message :%s\n", clientname, recvbuf);
//將接收到的資訊加密返回給客戶端
for (i=0; i='a' && recvbuf[i]<='z') || (recvbuf[i]>='a' && recvbuf[i]<='z'))
}sendbuf[i] = recvbuf[i];
} sendbuf[num-1] = '\0';
send(connfd, sendbuf, maxsize, 0);
} close(connfd);
return 1;
}int main(int argc, char **argv)
int opt = so_reuseaddr;
setsockopt(listenfd, sol_socket, so_reuseaddr, &opt, sizeof opt);
bzero(&serversock, sizeof serversock);
serversock.sin_family = af_inet;
serversock.sin_port = htons(port);
serversock.sin_addr.s_addr = htonl(inaddr_any);
if (bind(listenfd, (struct sockaddr *)&serversock, sizeof serversock) < 0)
if (listen(listenfd, 5) < 0)
len = (socklen_t)(sizeof clientsock);
while (1)
//建立子程序處理客戶端的資訊
if ((pid = fork()) > 0)
else if (pid == 0)
else
}close(listenfd);
}
客戶端**:
#include #include #include #include #include #include #include #include #include #define port 1234
#define maxsize 1024
static int clientprocess(file *fp, int connfd)
send(connfd, readline, maxsize, 0);
while (fgets(readline, maxsize, fp) != null)
send(connfd, readline, strlen(readline), 0);
num = recv(connfd, recvline, maxsize, 0);
if (num < 0)
recvline[num-1] = '\0';
printf("server message:%s\n", recvline);
} return 1;
}int main(int argc, char **argv)
he = gethostbyname(argv[1]);
if (he == null)
sockfd = socket(af_inet, sock_stream, 0);
if (sockfd < 0)
bzero(&serversock, sizeof serversock);
serversock.sin_family = af_inet;
serversock.sin_port = htons(port);
serversock.sin_addr = *((struct in_addr *)he->h_addr);
if (connect(sockfd, (struct sockaddr *)&serversock, sizeof serversock) < 0)
clientprocess(stdin, sockfd);
close(sockfd);
return 1;
}
程式實現的功能很簡單,**寫的也比較通俗易懂,基本上沒什麼注釋!**在我自己的虛擬機器裡面除錯通過,編譯即可執行!
網路程式設計基礎 併發程式設計 多程序
python中的多執行緒無法利用多核優勢,如果想要充分地使用多核cpu的資源 os.cpu count 檢視 在python中大部分情況需要使用多程序。python提供了multiprocessing multiprocessing模組用來開啟子程序,並在子程序中執行我們定製的任務 比如函式 該模組...
Linux網路程式設計多程序模型
include include include include include include include define serv port 8080 define maxline 100 define maxsize 4096 void sys error const char fun str...
python併發程式設計 多程序
import os import time from multiprocessing import process def func args,args2 print args,args2 time.sleep 3 print 子程序 os.getpid print 子程序的父程序 os.getpp...