DEVsocket编程
时间: 2023-10-15 14:23:30 浏览: 29
Socket编程是一种在计算机网络之间进行通信的方式。它允许客户端和服务器之间通过传输层协议(如TCP或UDP)进行数据交换。使用Socket编程,我们可以实现网络应用程序,如聊天应用、文件传输等。
在开发中,Socket编程可以使用不同的编程语言,如C、C++、Python等。以下是一个简单的C语言Socket编程示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
int main() {
int sockfd, newsockfd, clientLen;
char buffer[1024];
struct sockaddr_in serverAddr, clientAddr;
// 创建套接字
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = INADDR_ANY;
// 绑定地址和端口
if (bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
perror("Binding failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(sockfd, 5) < 0) {
perror("Listening failed");
exit(EXIT_FAILURE);
}
printf("Listening on port %d...\n", PORT);
clientLen = sizeof(clientAddr);
// 接受客户端连接
newsockfd = accept(sockfd, (struct sockaddr*)&clientAddr, &clientLen);
if (newsockfd < 0) {
perror("Accept failed");
exit(EXIT_FAILURE);
}
// 从客户端接收消息
memset(buffer, '\0', sizeof(buffer));
read(newsockfd, buffer, sizeof(buffer));
printf("Received message: %s\n", buffer);
// 发送响应消息给客户端
char response[] = "Server received your message";
write(newsockfd, response, sizeof(response));
close(newsockfd);
close(sockfd);
return 0;
}
```
这是一个简单的TCP服务器程序,它创建一个套接字、绑定到特定地址和端口、监听连接并接受客户端连接。然后,它从客户端接收消息,并发送响应消息。
当然,这只是一个基本的示例,Socket编程还涉及到更多的概念和功能,例如多线程处理、错误处理等。如果需要更深入了解Socket编程,请参考相关的文档和教程。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)