Skip to content

Instantly share code, notes, and snippets.

@GSkouroupathis
Created October 15, 2013 12:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save GSkouroupathis/6990853 to your computer and use it in GitHub Desktop.
Sets up a communication between the server and the client. The server side receives messages and the client side sends it.
#CLIENT.PY BY GEORGE SKOUROUPATHIS
from socket import *
HOST = 'localhost'
PORT = 2333
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
print 'Type "exit" without the quotes to quit the program.'
while 1:
#Input the message
message = raw_input('Type your message, client: ')
if message == "exit":
tcpCliSock.send('exit')
break
msglength = len(message)
#Make msglength a 4-byte string
if len(str(msglength)) == 1:
msglength = "000" + str(msglength)
elif len(str(msglength)) == 2:
msglength = "00" + str(msglength)
elif len(str(msglength)) == 3:
msglength = "0" + str(msglength)
#Part of the mesage which has been sent
msgsent = 0
#Send the length of the message in 4-digit format
while msgsent < 4:
sent = tcpCliSock.send(msglength[msgsent:])
msgsent += sent
#Part of the mesage which has been sent
msgsent = 0
#Send the message
while msgsent < int(msglength):
sent = tcpCliSock.send(message)
msgsent += sent
tcpCliSock.close()
#SERVER.PY BY GEORGE SKOUROUPATHIS
from socket import *
HOST = 'localhost'
PORT = 2333
BUFSIZ = 1024
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)
print "Awaiting connection..."
clientsock, addr = serversock.accept()
print "Connection from ", ADDR, "..."
while 1:
#Recieve message length in string format
msglength = ''
chunk = ''
while len(msglength) < 4:
chunk = clientsock.recv(4)
msglength += chunk
#Convert msglength to an integer
msglength = int(msglength)
#Recieve message
message = ''
while len(message) < msglength:
chunk = clientsock.recv(BUFSIZ)
message += chunk
if message == "exit":
break
print " - Client Says:"
print message
clientsock.close()
serversock.close()
testword = raw_input('Connection interrupted. Press any button to exit.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment