写了一个简单的socket客户端/服务器程序, 放在了github上
程序代码:
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> int main(int argc, char *argv[]) { int mySocket = socket(AF_INET, SOCK_STREAM, 0); struct hostent *host_entry = gethostbyname("localhost"); struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(7640); server.sin_addr.s_addr = *(unsigned long*) host_entry->h_addr; connect(mySocket, (struct sockaddr*)&server, sizeof(server)); #define MESSAGE_SIZE 24 char inMessage[MESSAGE_SIZE] = {0}; char outMessage[MESSAGE_SIZE] = "I sent you this message"; int nBytes = send(mySocket, outMessage, sizeof(outMessage), 0); printf("Message Sent : %s\n", outMessage); nBytes = recv(mySocket, inMessage, sizeof(inMessage), 0); printf("Message Received : %s\n", inMessage); close(mySocket); return 0; }
程序代码:
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> int main(int argc, char *argv[]) { int serverSocket = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(7640); server.sin_addr.s_addr = INADDR_ANY; bind(serverSocket, (struct sockaddr*)&server, sizeof(server)); listen(serverSocket, 5); int clientSocket = accept(serverSocket, 0, 0); #define MESSAGE_SIZE 24 char inMessage[MESSAGE_SIZE] = {}; char outMessage[MESSAGE_SIZE] = "I received your message"; int nBytes = recv(clientSocket, inMessage, sizeof(inMessage), 0); printf("Message Received : %s\n", inMessage); nBytes = send(clientSocket, outMessage, sizeof(outMessage), 0); printf("Message Sent : %s\n", outMessage); close(clientSocket); close(serverSocket); return 0; }
[此贴子已经被作者于2015-12-19 00:36编辑过]