python基于C/S模式实现聊天室功能
程序员文章站
2022-07-18 20:52:53
最简单的模式,c/s模式实现聊天室
从半双工开始,何谓半双工?半双工即是说双方可以互发消息,但一次只能一个用户发送。
只要稍微会点socket编程的人都会觉...
最简单的模式,c/s模式实现聊天室
从半双工开始,何谓半双工?半双工即是说双方可以互发消息,但一次只能一个用户发送。
只要稍微会点socket编程的人都会觉得很简单,所以过过场,直接上代码。
服务器端代码:
from socket import * from time import ctime host = '' port = 4568 bufsize = 1024 addr = (host,port) tcpsersocket = socket(af_inet, sock_stream) tcpsersocket.bind(addr) tcpsersocket.listen(5) while true: print('waitint for connection...') tcpclisocket, addr = tcpsersocket.accept() print('connecting from: ', addr) while true: data = tcpclisocket.recv(bufsize) if not data: break print data msg = raw_input('>') tcpclisocket.send('[%s] %s' % (ctime(), msg)) tcpclisocket.close() tcpsersocket.close()
客户端代码:
from socket import * host = 'localhost' port = 4568 bufsize = 1024 addr = (host, port) tcpclisocket = socket(af_inet, sock_stream) tcpclisocket.connect(addr) while true: data = raw_input('>>') if not data: break tcpclisocket.send(data) data = tcpclisocket.recv(bufsize) if not data: break print data tcpclisocket.close()
运行结果我就不截图了,如果还不会的就复制下来运行一遍。
上面只是最简单的入门,一点都不好使,问题多着。
下面看怎么实现全双工。全双工就是双方可任意给对方发送消息。
全双工明显要用到多线程。我们在主线程之外创建两个子线程,一个负责接收消息,另一个负责接受用户输入并发送消息。
服务器端代码:
#coding: utf-8 from socket import * from time import ctime import threading from sys import stdout host = '' port = 21567 bufsize = 1024 addr = (host, port) def send(sck): while true: data = raw_input('>') sck.send(data) def deal(sck, addr): while true: data = sck.recv(bufsize) if data == "quit": sck.close() break str = '\nfrom' + addr[0] + ':' + data + '\n>' stdout.write(str) chatsersock = socket(af_inet, sock_stream) chatsersock.bind(addr) chatsersock.listen(5) threads = [] while true: print 'waiting for connection...' chatclisock, addr = chatsersock.accept() print "...connected from: ", addr t = threading.thread(target=deal, args=(chatclisock, addr)) threads.append(t) t = threading.thread(target=send, args=(chatclisock,)) threads.append(t) for i in range(len(threads)): threads[i].start() threads[0].join() chatclisock.close() chatsersock.close()
客户端代码:
#coding: utf8 from socket import * from time import ctime import threading from sys import stdout def send(sck, test): while true: data = raw_input('>') sck.send(data) if data == "quit": break def recieve(sck, test): while true: data = sck.recv(bufsiz) if data == "quit": sck.close() break str = "\nfrom server:" + data + "\n>" stdout.write(str) host = 'localhost' port= 21567 bufsiz = 1024 addr = (host, port) threads = [] if __name__ == "__main__": chatclisock = socket(af_inet, sock_stream) chatclisock.connect(addr) t = threading.thread(target=send, args = (chatclisock, none)) threads.append(t) t = threading.thread(target=recieve, args = (chatclisock, none)) threads.append(t) for i in range(len(threads)): threads[i].start() threads[0].join() chatclisock.close()
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: PHP 飞信好友免费短信API接口开源版