Last active
August 10, 2017 23:02
-
-
Save tuxmartin/9e76879bdf809379f5a02a88b3b25ec2 to your computer and use it in GitHub Desktop.
ukazkovy server z http://www.binarytides.com/python-socket-server-code-example/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import sys | |
from thread import * | |
HOST = '' # Symbolic name meaning all available interfaces | |
PORT = 2196 # Arbitrary non-privileged port | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
print 'Socket created' | |
#Bind socket to local host and port | |
try: | |
s.bind((HOST, PORT)) | |
except socket.error as msg: | |
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] | |
sys.exit() | |
print 'Socket bind complete' | |
#Start listening on socket | |
s.listen(10) | |
print 'Socket now listening' | |
#Function for handling connections. This will be used to create threads | |
def clientthread(conn): | |
#Sending message to connected client | |
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string | |
#infinite loop so that function do not terminate and thread do not end. | |
while True: | |
#Receiving from client | |
data = conn.recv(1024) | |
print data | |
conn.sendall("abc123") | |
#came out of loop | |
conn.close() | |
#now keep talking with the client | |
while 1: | |
#wait to accept a connection - blocking call | |
conn, addr = s.accept() | |
print 'Connected with ' + addr[0] + ':' + str(addr[1]) | |
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function. | |
start_new_thread(clientthread ,(conn,)) | |
s.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment