Socket 编程是 Linux 应用程序中常用的一种网络编程方式。通过使用套接字(Socket),可以实现进程间的通信和网络通信。常见的 Socket 编程包括创建套接字、绑定地址、监听连接、接受连接、发送和接收数据等操作。
<p>#include <sys/socket.h></p><p>#include <netinet/in.h></p><p>#include <unistd.h></p><p>#include <iostream></p><p>
</p><p>int main() {</p><p> // 创建套接字</p><p> int serverSocket = socket(AF_INET, SOCK_STREAM, 0);</p><p>
</p><p> // 绑定地址</p><p> sockaddr_in serverAddress;</p><p> serverAddress.sin_family = AF_INET;</p><p> serverAddress.sin_port = htons(8080);</p><p> serverAddress.sin_addr.s_addr = INADDR_ANY;</p><p> bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress));</p><p>
</p><p> // 监听连接</p><p> listen(serverSocket, 5);</p><p>
</p><p> // 接受连接</p><p> int clientSocket = accept(serverSocket, NULL, NULL);</p><p>
</p><p> // 发送和接收数据</p><p> char buffer[256];</p><p> read(clientSocket, buffer, sizeof(buffer));</p><p> std::cout << "Received: " << buffer << std::endl;</p><p> write(clientSocket, "Hello from server!", 18);</p><p>
</p><p> // 关闭套接字</p><p> close(clientSocket);</p><p> close(serverSocket);</p><p>
</p><p> return 0;</p><p>}</p>
|