python socket 聊天室

 

 

 

 

服务端

# coding: utf-8


import socket
import threading

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 8000))
server.listen()


# 获取从客户端发送的数据

def handle_sock(sock, addr):
    while True:
        data = sock.recv(1024)
        print(data.decode("utf-8"))
        re_data = input()
        sock.send(re_data.encode("utf-8"))


while True:
    sock, addr = server.accept()

    # 用线程 去处理新接受的连接(用户)
    client_thread = threading.Thread(target=handle_sock, args=(sock, addr))
    client_thread.start()

    # data = sock.recv(1024)
    # print(data.decode("utf-8"))
    # re_data = input()
    # sock.send(re_data.encode("utf-8"))

# server.close()
# sock.close()

 

客户端

# coding: utf-8

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 8000))

while True:
    re_data = input()
    client.send(re_data.encode("utf-8"))
    data = client.recv(1024)
    print(data.decode("utf-8"))

# client.close()

 

posted @ 2020-08-02 17:11  AngDH  阅读(496)  评论(0编辑  收藏  举报