消息队列是可以实现没有共同关系的进程之间的通信。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);
服务器接收来自客户的信息:
客户发送信息:
客户端代码:
#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 = -1; struct sockaddr_in address; //创建套接字 sockfd = socket(AF_INET, SOCK_STREAM, 0); //对地址结构体赋值 address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr("127.0.0.1"); address.sin_port = htons(9030); //连接服务器的时候 要把套接字和地址结构传进去 connect(sockfd, (struct sockaddr*)&address, sizeof(address)); printf("Connect OK! "); printf("Enter a string "); char buffer[256]; memset(buffer,'