Ubuntu启一个tcp server,client去连接

1、在~/source/code/python目录下创建两个py文件:

server_8079.py、client_8079.py

server_8079.py的代码:

python 复制代码
# server.py
import socket

def start_server(host, port):
    # 创建一个TCP/IP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # 绑定套接字到地址和端口
    server_socket.bind((host, port))
    
    # 监听传入连接
    server_socket.listen(1)
    print(f"Server listening on {host}:{port}")
    
    while True:
        # 等待连接
        client_socket, addr = server_socket.accept()
        try:
            print(f"Connection from {addr}")
            
            # 接收数据
            data = client_socket.recv(1024)
            print(f"Received: {data.decode('utf-8')}")
            
            # 发送响应
            response = "Hello from server!"
            client_socket.sendall(response.encode('utf-8'))
        finally:
            # 清理连接
            client_socket.close()

if __name__ == "__main__":
    HOST = '192.168.111.128'
    PORT = 8079
    start_server(HOST, PORT)

client_8079.py的代码:

python 复制代码
# client.py
import socket

def start_client(host, port):
    # 创建一个TCP/IP套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    try:
        # 连接到服务器
        client_socket.connect((host, port))
        
        # 发送数据
        message = "Hello from client!"
        client_socket.sendall(message.encode('utf-8'))
        
        # 接收响应
        response = client_socket.recv(1024)
        print(f"Received: {response.decode('utf-8')}")
    finally:
        # 清理连接
        client_socket.close()

if __name__ == "__main__":
    HOST = '192.168.111.128'
    PORT = 8079
    start_client(HOST, PORT)

打开2个terminal:

在第1个terminal输入:

python3 server_8079.py

在第2个terminal输入:

python3 client_8079.py

相关推荐
Gauss松鼠会4 小时前
【GaussDB】技术解读|GaussDB架构介绍
数据库·架构·数据库开发·gaussdb
星空露珠4 小时前
迷你世界UGC3.0脚本Wiki世界模块管理接口 World
开发语言·数据库·算法·游戏·lua
zdl6864 小时前
spring Profile
java·数据库·spring
Gauss松鼠会4 小时前
【GaussDB】GaussDB 表的创建与使用之临时表
数据库·database·opengauss·gaussdb
RestCloud4 小时前
Oracle CDC实战:如何构建企业级实时数据同步架构
数据库·oracle·etl·etlcloud·数据同步·数据集成平台
zhougl9964 小时前
Maven build配置
java·linux·maven
Predestination王瀞潞4 小时前
CentOS7虚拟机安装过程中没有打开网卡,ip addr无法查看es33这个情况下的解决方法
服务器·网络·tcp/ip
dgfhf4 小时前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
૮・ﻌ・4 小时前
Node.js - 04:MongoDB、会话控制
数据库·mongodb·node.js·jwt·token·cookie·session
闻哥4 小时前
MySQL三大日志深度解析:redo log、undo log、binlog 原理与实战
android·java·jvm·数据库·mysql·adb·面试