python-半双工聊天程序

直接导入socket的简单、基础的半双工聊天程序

server端:

​
import socket

#创建连接socket
s_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#绑定地址及端口
s_socket.bind((\"127.0.0.1\",6667))
#监听
s_socket.listen(1)#排队序列最大值
#获取客户端的请求并新建通信(数据)socket
D_socket,addr=s_socket.accept()
print(addr)

while True:
    #接收客户端的信息
    msg=D_socket.recv(1024).decode()#1024为能够接收的最大字节数
    if not msg:
        continue;
    elif msg==\'quit\':#当收到quit后关闭D_socket并等待下次连接
        break;
    else:
        print(msg)
        while True:
            s_msg=input(\'zhangsan:\')
            if not s_msg:
                continue
            else:
                D_socket.send(\'{}:{}\'.format(\"zhangsan\",s_msg).encode())
                break
s_socket.close()

​

client端:

import socket
tryConn=0
#创建连接socket
s_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#连接服务器端
while True:
    s_socket.connect((\"127.0.0.1\",6667))
    tryConn=tryConn+1
    if tryConn==3:
        print(\"无法尝试连接远程主机,请稍后再试\")
        exit()
    else:
        print(\"连接成功\")
        break
while True:
    data=input(\"lisi:\") 
    if not data:
        continue
    elif data==\'quit\':#通知服务端工作完成
        s_socket.send(\'{}:{}\'.format(\"lisi\",data).encode())
        break
    else:
        s_socket.send(\'{}:{}\'.format(\"lisi\",data).encode())
        while True:
            data=s_socket.recv(1024).decode()
            if not data:
               continue
            else:
                print(data)
                break
s_socket.close()

 

收藏 打印