简单的局域网聊天程序

LANTalk模块(LANTalk.py)

def sender(tcpSock1, mutex, name):
    while 1:
        mutex.acquire()
        data = input('')
        data1 = name+':'+data
        tcpSock1.send(data1.encode('utf8'))
        mutex.release()
       
def reciver(tcpSock2, bufsize, mutex):
    while 1:
        mutex.acquire(0)
        data2 = tcpSock2.recv(bufsize)
        print(data2.decode())
        mutex.release()

 

LANTalk服务器端(LANTalk_ser.py)

from socket import *
from time import time, ctime, sleep
from LANTalk import sender, reciver
import _thread

def main():
    HOST = ''
    PORT = 21567
    BUFSIZE = 1024
    ADDR = (HOST, PORT)
    NAME = 'JACK'

    tcpSerSock = socket(AF_INET, SOCK_STREAM)
    tcpSerSock.bind(ADDR)
    tcpSerSock.listen(5)

    print('waiting for connection1...')
    tcpSock1, addr1 = tcpSerSock.accept()
    print('...connected form:', addr1)
    print('waiting for connection2...')
    tcpSock2, addr2 = tcpSerSock.accept()
    print('...connected form:', addr2)

    mutex = _thread.allocate_lock()
    _thread.start_new_thread(reciver,(tcpSock1, BUFSIZE, mutex))
    _thread.start_new_thread(sender,(tcpSock2, mutex, NAME))
    sleep(1000)
   
    tcpSerSock.close()

if __name__ == '__main__':
    main()

 

LANTalk客户端(LANTalk_cli.py)

from socket import *
from time import time, ctime, sleep
from LANTalk import sender, reciver
import _thread

def main():
    HOST = '192.168.1.111'
    PORT = 21567
    BUFSIZE = 1024
    ADDR = (HOST, PORT)
    NAME = 'LUCY'

    tcpSock2 = socket(AF_INET, SOCK_STREAM)
    tcpSock2.connect(ADDR)
    print('connected...2')
    sleep(3)
    tcpSock1 = socket(AF_INET, SOCK_STREAM)
    tcpSock1.connect(ADDR)
    print('connected...1')

    mutex = _thread.allocate_lock()
    _thread.start_new_thread(sender,(tcpSock2, mutex, NAME))
    _thread.start_new_thread(reciver,(tcpSock1, BUFSIZE, mutex))
    sleep(1000)

    tcpSock2.close()
    tcpSock1.close()

if __name__ == '__main__':
    main()

 

涉及到网络程序设计和多线程程序设计,但该程序功能过于简单,有待改进和完善:如服务器定位,多人聊天等问题,最好是引入GUI程序设计做出界面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值