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程序设计做出界面。