Python的socket聊天脚本。

zluxingzhe 2019-12-08

没有前端,多开了一条线程用于接收信息。

服务器端:

# -*- coding:utf-8 -*-
import socket
import threading

class Sock_Server:
    def __init__(self):
        self.host = ‘192.168.1.11‘  # 获取主机名
        self.port = 12345  # 端口
        self.ser = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 设置模式
        self.ser.bind((self.host, self.port))
        self.ser.listen(5)
        print(‘等待客户端连接:‘)
        self.sock, self.addr = self.ser.accept()        # 被动接口客户端连接。
        print(f‘客户:{self.addr},已经连接‘)

    def recv(self):           # 接收信息模块
        try:
            while True:
                recv_info = self.sock.recv(1024)
                if recv_info:
                    print(‘\n收到消息:‘, recv_info.decode())
                    if recv_info == ‘886‘:
                        self.sock.close()
                        self.ser.close()
                        print(‘聊天结束!over‘)
                        break
        finally:
            self.sock.close()
            self.ser.close()

    def send(self):
        try:
            while True:
                send_info = input(‘请输入你要发送的内容:‘)
                self.sock.send(send_info.encode())
                if send_info == ‘886‘:
                    self.sock.close()
                    self.ser.close()
                    print(‘聊天结束!over‘)
                    break
        finally:
            self.sock.close()
            self.ser.close()



if __name__ == ‘__main__‘:
    sock = Sock_Server()
    t1 = threading.Thread(target=sock.recv)
    t1.start()
    sock.send()

 客户端:

# -*- coding:utf8 -*-
import socket
import threading

class Sock_Cli:
    def __init__(self):
        self.host = socket.gethostname()  # 获取主机名
        self.port = 12345  # 端口
        self.ser = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 设置模式
        self.ser.connect((self.host, self.port))

    def recv(self):           # 接收信息模块
        try:
            while True:
                recv_info = self.ser.recv(1024)
                if recv_info:
                    print(‘\n收到消息:‘, recv_info.decode())
                    if recv_info == ‘886‘:
                        self.ser.close()
                        print(‘聊天结束!over‘)
                        break
        finally:
            self.ser.close()

    def send_info(self):
        try:
            while True:
                send_info = input(‘请输入你要发送的内容:‘)
                self.ser.sendall(send_info.encode())
                if send_info == ‘886‘:
                    self.ser.close()
                    print(‘聊天结束!over‘)
                    break
        finally:
            self.ser.close()


if __name__ == ‘__main__‘:
    cli = Sock_Cli()
    t1 = threading.Thread(target=cli.recv)
    t1.start()
    cli.send_info()

 socket是进程间进行通讯很好的方式。

整个代码在886输入退出还存在一些问题,不改了。

相关推荐