Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

socket python

作者:似水韶华该惜谁ら   发布日期:2025-10-17   浏览:4

import socket

# 创建一个socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定主机和端口
host = '127.0.0.1'
port = 12345
server_socket.bind((host, port))

# 监听连接
server_socket.listen(5)
print(f"服务器正在监听 {host}:{port}")

# 接受客户端连接
client_socket, addr = server_socket.accept()
print(f"收到连接请求来自: {addr}")

# 接收客户端消息
message = client_socket.recv(1024).decode('utf-8')
print(f"收到消息: {message}")

# 发送回复消息
reply = "Hello, Client!"
client_socket.send(reply.encode('utf-8'))

# 关闭连接
client_socket.close()
server_socket.close()

解释说明:

  1. 创建Socket对象:使用socket.socket()创建一个TCP/IP套接字。
  2. 绑定地址和端口:使用bind()方法将套接字绑定到指定的IP地址和端口号。
  3. 监听连接:使用listen()方法使服务器开始监听传入的连接请求,参数表示最大等待队列长度。
  4. 接受客户端连接:使用accept()方法阻塞等待客户端连接,返回一个新的套接字对象和客户端地址。
  5. 接收数据:使用recv()方法从客户端接收数据,解码为字符串。
  6. 发送数据:使用send()方法向客户端发送数据,编码为字节流。
  7. 关闭连接:使用close()方法关闭套接字,释放资源。

上一篇:python str 转json

下一篇:pythonset

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站