python socket实现服务器客户端聊天

运行效果:

服务端:

python socket实现服务器客户端聊天_第1张图片

客户端:

python socket实现服务器客户端聊天_第2张图片python socket实现服务器客户端聊天_第3张图片

服务端:

import socket

print("程序开始")
#   创建套接字
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#   设置IP和端口
host = socket.gethostname()
port = 3333
#   bind绑定该端口
mySocket.bind((host, port))
#   监听
mySocket.listen(10)

while True:
    #   接收客户端连接
    print("等待连接....")
    client, address = mySocket.accept()
    print("新连接")
    print("IP is %s" % address[0])
    print("port is %d\n" % address[1])

    while True:
        #   发送消息
        msg = input("----------------------发送:")
        client.send(msg.encode())
        print("发送完成")
        if msg == "EOF":
            break
        if msg == "quit":
            client.close()
            mySocket.close()
            print("程序结束\n")
            exit()
        #   读取消息
        msg = client.recv(1024)
        print("----------------------读取:", msg)
        print("读取完成")
        if msg == b"EOF":
            break
        if msg == b"quit":
            client.close()
            mySocket.close()
            print("程序结束\n")
            exit()


客户端:

import socket

print("程序开始")

#   创建套接字
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#   设置ip和端口
host = socket.gethostname()
port = 3333
#   连接到服务器
mySocket.connect((host, port))
print("连接到服务器")

while True:
    #   接收消息
    print("----------------------读取:", end="")# 不换行输出
    msg = mySocket.recv(1024)
    print("%s" % msg)
    print("读取完成")
    if msg == b"EOF":
        break
    if msg == b"quit":
        mySocket.close()
        print("程序结束\n")
        exit()

    #   发送消息
    msg = input("----------------------发送:")
    mySocket.send(msg.encode())
    print("发送完成")
    if msg == "EOF":
        break
    if msg == "quit":
        mySocket.close()
        print("程序结束\n")
        exit()
print("程序结束\n")

注意错误:TypeError: a bytes-like object is required, not 'str' 

解决方法:

b'msg'或者如下

msg = input("----------------------发送:")
client.send(msg.encode())
msg = client.recv(1024)
print("----------------------读取:", msg)

你可能感兴趣的:(python)