linux 进程通信 :流套接字

消息队列是可以实现没有共同关系的进程之间的通信。Socket则可以实现不同计算机的不同进程之间的通信。

//地址的结构体
struct sockaddr_in{
short int sin_family;//AF_INET
unsigned short int sin_port;//端口号
struct in_addr sin_addr;//IP地址
}; struct in_addr{
unsigned long int s_addr;
};

几个重要的函数:

//创建socket
int socket(int domain, int type, int protocol); //命名(绑定)套接字 服务器采用
int bind( int socket, const struct sockaddr *address, size_t address_len); //创建套接字队列(监听)
int listen(int socket, int backlog); //接受连接
int accept(int socket, struct sockaddr *address, size_t *address_len); //请求连接
int connect(int socket, const struct sockaddr *address, size_t address_len);

服务器接收来自客户的信息:

linux 进程通信 :流套接字

客户发送信息:

linux 进程通信 :流套接字

客户端代码:

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h> int main(){ int sockfd = -;
struct sockaddr_in address; //创建套接字
sockfd = socket(AF_INET, SOCK_STREAM, ); //对地址结构体赋值
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(); //连接服务器的时候 要把套接字和地址结构传进去
connect(sockfd, (struct sockaddr*)&address, sizeof(address)); printf("Connect OK!\n"); printf("Enter a string\n"); char buffer[];
memset(buffer,'\0',); fgets(buffer,,stdin); //socketfd的用处在这里,通过write和read来读写数据 write(sockfd,buffer,); memset(buffer,'\0',); read(sockfd,buffer,); printf("%s\n",buffer); close(sockfd); }

服务端代码:

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h> int main(){ int server_sockfd = -;
int client_sockfd = -; struct sockaddr_in server_addr;
struct sockaddr_in client_addr; server_sockfd = socket(AF_INET, SOCK_STREAM, );
//internet stream protocol server_addr.sin_family = AF_INET;
//接收任何地址
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(); //绑定才能被别人找到
bind(server_sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)); //创建队列
listen(server_sockfd, ); //create end while(){ printf("Server start!\n"); char buffer[];
memset(buffer,'\0',); int client_len = sizeof(client_addr); //接收成功会返回客户的文件描述符 把客户的地址信息填到client_addr里面
client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_addr, &client_len); //调用子进程来处理
if(fork()==){ //in child process read(client_sockfd,buffer,); printf("client:\n");
printf("%ld\n",client_addr.sin_addr.s_addr);
printf("%d\n",client_addr.sin_port);
printf("Message:%s\n",buffer); write(client_sockfd,"Get Message\n",); close(client_sockfd); }
else{ close(client_sockfd); } } }
上一篇:express 框架之 路由与中间件


下一篇:at