Python编程·一个最简单的socket聊天工具

这是一个极为简单的聊天工具,需要python3运行环境,通过socket传输消息,服务端保留聊天记录,那些想私密聊天的可以拿去玩一玩。

服务端代码:

#!/usr/bin/python3
# _*_ coding: UTF-8 _*_

import socket
import time
from urllib.request import urlopen
from json import load

def getip():
    pubip = load(urlopen('http://jsonip.com'))['ip']
    print('服务端IP为' + pubip + ':8080,请确保公网服务可用\n等待客户端发送消息>>>')

def schat():
    skt = socket.socket()
    skt.bind(('0.0.0.0',8080))
    skt.listen()

    conn,addr = skt.accept()

    while 1:
        msg_rec = conn.recv(1024).decode('utf-8')
        print(msg_rec)
        with open('record.txt','a',encoding='UTF-8') as f:
            ntime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            f.write(ntime+' | '+msg_rec+'\n')
            f.close()
        msg_snd = input('> ')
        conn.send(msg_snd.encode('utf-8'))
        with open('record.txt','a',encoding='UTF-8') as f:
            ntime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            f.write(ntime+' | '+msg_snd+'\n')
            f.close()

    conn.close()
    skt.close()

if __name__ == '__main__':
    getip()
    schat()

客户端代码:

#!/usr/bin/python3
# _*_ coding: UTF-8 _*_

import socket

def cchat():
    skt = socket.socket()
    # 请修改为服务端实际IP和端口
    skt.connect(('10.10.10.203',8080))

    while 1:
       msg_snd = input('> ')
       skt.send(msg_snd.encode('utf-8'))
       if msg_snd == 'q':
           break
       msg_rec = skt.recv(1024).decode('utf-8')
       if msg_rec == 'q':
           break
       print(msg_rec)

    skt.close()

if __name__ == '__main__':
    cchat()

原创文章禁止转载:技术学堂 » Python编程·一个最简单的socket聊天工具

精彩评论

5+4=

感谢您的支持与鼓励

支付宝扫一扫打赏

微信扫一扫打赏