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

python tcp server

作者:爱我者我必爱*   发布日期:2025-11-23   浏览:57

# Python TCP Server 示例代码

import socket

def start_tcp_server(host='127.0.0.1', port=65432):
    # 创建一个TCP/IP套接字
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
        # 绑定套接字到指定的地址和端口
        server_socket.bind((host, port))
        # 监听传入连接
        server_socket.listen()
        print(f"Server started on {host}:{port}")

        while True:
            # 等待客户端连接
            conn, addr = server_socket.accept()
            with conn:
                print(f"Connected by {addr}")
                while True:
                    # 接收数据
                    data = conn.recv(1024)
                    if not data:
                        break
                    # 发送响应
                    conn.sendall(data)

if __name__ == "__main__":
    start_tcp_server()

解释说明:

  1. 导入模块socket 模块用于创建和管理网络连接。
  2. 创建套接字:使用 socket.socket() 创建一个TCP套接字,参数 AF_INET 表示使用IPv4地址,SOCK_STREAM 表示使用TCP协议。
  3. 绑定地址和端口:使用 bind() 方法将套接字绑定到指定的IP地址和端口号。
  4. 监听连接:使用 listen() 方法使服务器开始监听传入连接。
  5. 接受连接:使用 accept() 方法等待并接受客户端连接,返回一个新的套接字对象和客户端地址。
  6. 接收和发送数据:使用 recv() 方法接收客户端发送的数据,使用 sendall() 方法将数据回显给客户端。
  7. 关闭连接:当没有更多数据时,关闭连接。

这个简单的TCP服务器会回显它从客户端接收到的所有数据。

上一篇:python 矩阵相乘

下一篇:python解释器路径

大家都在看

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 中文站