Hello everyone, today talk about python socket programming, based on the python socket communication text box webchat
First.Experimental environment:
A cloud server (we're using AliCloud here, so you'll be on your own terms);
Unix-like operating systems (e.g. Mac OS, Linux, etc.);
Windows family of operating systems.
Here, I'm using AliCloud, Mac OSX, Windows XP (a VM on a mac).
# -*- coding: utf-8 -*- #!/usr/local/bin/python import socket import sys import threading con = () HOST = "The IP address of CloudSpace." PORT = ports data = '' s = (socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' ((HOST, PORT)) (10) print 'Socket now listening' def clientThreadIn(conn, nick):#open thread global data while True:# Accept client data try: temp = (1024) if not temp: ()#Connection closed return NotifyAll(temp) print data except: NotifyAll(nick + " leaves the room!") print data return def NotifyAll(sss):#Broadcasting global data if (): data = sss () () def ClientThreadOut(conn, nick):# Client output global data while True: if (): () if data: try: (data) () except: () return while 1: conn, addr = () print 'Connected with ' + addr[0] + ':' + str(addr[1]) nick = (1024) NotifyAll('Welcome ' + nick + ' to the room!') print data print str((() + 1) / 2) + ' person(s)!' (data) (target = clientThreadIn , args = (conn, nick)).start()#open thread (target = ClientThreadOut , args = (conn, nick)).start() ()
# -*- coding: utf-8 -*- import socket import threading import getpass inString = '' outString = '' nick = '' def DealOut(s): computername=()# Get the computer name global nick, outString while True: outString = raw_input(nick+":") outString = nick + "@" + computername + ': ' + outString (outString) def DealIn(s): global inString while True: try: inString = (1024) if not inString: break if outString != inString: print inString except: break nick = ()# Get the operating system username ip = "Cloud space IP address." sock = (socket.AF_INET, socket.SOCK_STREAM) ((ip, ports)) (nick) thin = (target = DealIn, args = (sock,))#Open a read-in thread () thout = (target = DealOut, args = (sock,))#open a write-out thread ()
It will be uploaded to the cloud and run, as shown:
will run on a mac system as shown:
will run on a WindowsXP virtual machine as shown:
OK, that's it, a textbox web chat room based on python socket communication is written.
This is the whole content of this article.