I'm trying to build up a non-blocking UDP-Server that listens to different ports and receives data-packages until timeout. Unfortunatly, I cannot change the client-side and UDP is mandatory.
Receiving files works fine. The issue is, that creating the workers is a blocking operation. I'd like to have it non-blocking so all workers are called in parallel. Also each worker should run in a loop like while True but that was blocking, too.
Here is my code:
#!/usr/bin/env python
from socket import *
import sys
import select
import threading
threads = []
def worker(port):
host="192.168.88.51"
s = socket(AF_INET,SOCK_DGRAM)
s.bind((host,port))
addr = (host,port)
buf=128
data,addr = s.recvfrom(buf)
filename = str(port)+".data"
print str(port)+" received File:"
f = open(filename,'wb')
data, addr = s.recvfrom(buf)
try:
while(data):
f.write(data)
s.settimeout(1)
data,addr = s.recvfrom(buf)
except timeout:
f.close()
s.close()
print "File Downloaded"
for i in range(1300,1305):
wrk = worker(i)
threads.append(wrk)
This will work as you intended except that it will overwrite the file a new each time new data is sent without timing out.
Timeout represents end of whole connection. But you can easily rework this to add data to same file or create a new file or do whatever you need.
#! /usr/bin/env python
from socket import AF_INET, SOCK_DGRAM
import socket
import threading
class Server (threading.Thread):
def __init__ (self, host="192.168.88.51", port=123, bufsize=128):
threading.Thread.__init__(self)
self.host = host
self.port = port
self.bufsize = bufsize
self.done = threading.Event()
def opensock (self):
s = socket.socket(AF_INET, SOCK_DGRAM)
s.bind((self.host, self.port))
s.settimeout(0.001)
return s
def run (self):
host = self.host
port = self.port
self.s = s = self.opensock()
print "Waiting for connection on", host+":"+str(port)
while not self.done.isSet():
try:
data, addr = s.recvfrom(self.bufsize)
print "Connection from", addr
s.settimeout(1)
self.recvdata(data, s, addr)
s.settimeout(0.001)
except socket.timeout: pass
except:
raise
self.done.set()
s.close()
print "Server on '%s:%s' stopped!" % (host, port)
def recvdata (self, initdata, conn, addr):
bufsize = self.bufsize
filename = str(self.port)+".data"
print "Opening file", filename
f = open(filename, "wb")
print "Receiving & writingrest of data from", addr
data = initdata
while data and not self.done.isSet():
f.write(data)
try:
data, addr = conn.recvfrom(bufsize)
except socket.timeout: break
f.close()
if self.done.isSet():
print "Forcefully interrupted transmission"
else:
print "File Downloaded"
def stop (self):
self.done.set()
self.s.close()
servers = []
for port in xrange(123, 150):
try:
s = Server(port=port)
s.start()
servers.append(s)
except Exception as e:
print e
raw_input("Press enter to send data to one of ports for testing . . . ")
import random
a = servers[0].host
p = random.choice(servers).port
print "data will be sent to port '%s:%i'" % (a, p)
k = socket.socket(AF_INET, SOCK_DGRAM)
k.connect((a, p))
k.send("1234567890")
k.send("asdfghjkl")
k.send("0987654321")
k.close()
raw_input("Press enter to close the program . . . ")
# Stop all servers:
for s in servers:
s.stop()
# Make sure all of them terminated:
for s in servers:
s.join()
That did it. Figured it out myself.
#!/usr/bin/env python
from socket import *
import sys
import select
import multiprocessing
def worker(port):
print "started: "+str(port)
host="192.168.88.51"
s = socket(AF_INET,SOCK_DGRAM)
s.bind((host,port))
addr = (host,port)
buf=128
data,addr = s.recvfrom(buf)
filename = str(port)+".jpg"
print str(port)+" received File:"
f = open(filename,'wb')
data, addr = s.recvfrom(buf)
try:
while(data):
f.write(data)
s.settimeout(1)
data,addr = s.recvfrom(buf)
except timeout:
f.close()
s.close()
print "File Downloaded"
for i in range(1300,1305):
multiprocessing.Process(target=worker, args=(i,)).start()
Related
So I have successfully created a socket connection to one client and another, but I am having trouble getting them to switch from one another with loops, did some while true and if statements to make the program recognize when one system wants to switch based on user input but I don't think I'm doing it right. Can some one help me out with a code to switch back and forth
The following is the code I'm attempting to implement.
This is the code on my computer:
import socket,sys,os,time
T2='yourturn'
serverAddr = ('192.168.0.120', 20104)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#client.connect(serverAddr)
sock = client
client.connect(('192.168.0.120', 20104))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def redirectOut(port=20104, host='192.168.0.11'):
"""
connect caller's standard output stream to a socket for GUI to listen
start caller after listener started, else connect fails before accept
"""
sock = client
# caller operates in client mode
file = sock.makefile('w') # file interface: text, buffered
sys.stdout = file
# make prints go to sock.send
return sock
########################################33333
time.sleep(10)
HOST = ''
PORT2 = 20105
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
l=s.bind((HOST, PORT2))
except socket.error as msg:
print('Bind failed. ')
sys.exit()
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
conn, addr = s.accept()
print('Connected to ' + addr[0] + ':' + str(addr[1]))
####################################################
time.sleep(10)
while True:
if T2!='yourturn':
data = conn.recv(1024)
line = data.decode # convert to string (Python 3 only)
T2=print(line)
else :
if T2=='myturn':
break
else:
redirectOut()
T2=print(input())
this is the code on my begalbone black:
import socket
import sys
import os, time
HOST = ''
PORT2 = 20104
T='yourturn'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
l=s.bind((HOST, PORT2))
except socket.error as msg:
print('Bind failed. ')
sys.exit()
print('Socket bind complete')
s.listen(10)
print('Socket now listening')
conn, addr = s.accept()
print('Connected to ' + addr[0] + ':' + str(addr[1]))
#################################################################
time.sleep(15)
serverAddr = ('192.168.0.11', 20105)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock = client
try:
sock.connect(('192.168.0.11', 20105))
fsr = 'P9_40'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except TimeoutError:
os.system('reboot')
def redirectOut(port=20105, host='192.168.0.120'):
"""
connect caller's standard output stream to a socket for GUI to listen
start caller after listener started, else connect fails before accept
"""
sock = client
# caller operates in client mode
file = sock.makefile('w') # file interface: text, buffered
sys.stdout = file # make prints go to sock.send
return sock
##############################################################
time.sleep(10)
while True:
if T!='myturn':
data = conn.recv(1024)
line = data.decode('UTF-8') # convert to string (Python 3 only)
T=print(line)
else:
redirectOut()
if T=='yourturn':
break
else:
T=print(input())
So tried this while loop: but its still hanging up, I think I'm close:
T2='yourturn'
while True:
#for line in 'Python':
print(T2)
time.sleep(10)
if T2=='myturn':
data = conn.recv(1024)
line = data.decode
print("myturn print")
l=print(line)
if l=="yourturn":
continue
if T2=="yourturn" or T2!='myturn':
print(T2)
print('myturn send')
redirectOut()# convert to string (Python 3 only)
k=input()
if k=="myturn":
T2='myturn'
continue
Tried the folowing but reciving machine is hanging up when myturn is input:
sending:
time.sleep(3)
T2='yourturn'
print('here')
while True:
#for line in 'Python':
#print(T2)
#time.sleep(10)
if T2=='myturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
#print("myturn print")
l=print(line)
if l=="yourturn":
T2='yourturn'
continue
if T2=="yourturn" and T2!='myturn':
#print(T2)
#print('myturn send')
redirectOut()# convert to string (Python 3 only)
k=input()
print(k)
if k=="myturn":
T2=print('myturn')
T2='myturn'
print('there')
continue
receiving:
time.sleep(3)
T='yourturn'
while True:
#for line in 'Python':
#print(T)
if T=='yourturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
#print("myturn print")
l=print(line)
if l=='myturn':
T='myturn'
continue
if l=='exit':
client.close()
break
if T=='myturn' and T!='yourturn':
#print('myturn send')
redirectOut()# convert to string (Python 3 only)
k=input()
print(k)
if k=='yourturn':
T=print('yourturn')
continue
EDIT SOLUTION:
I finally figured it out, removed my reditectOut function and opened the port with windows firewall to implement this code
my computer:
T2='yourturn'
while True:
if T2=='myturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
print(line)
l=line
if l=="yourturn":
T2='yourturn'
continue
if T2=="yourturn" and T2!='myturn':
k=input()
client.sendto(k.encode('utf-8'),('192.168.0.120', 20104))
if k=="myturn":
T2='myturn'
continue
Beagle bone black:
time.sleep(3)
T='yourturn'
while True:
if T=='yourturn':
data = conn.recv(1024)
line = data.decode('UTF-8')
print(line)
l=line
if l=='myturn':
T='myturn'
continue
if T=='myturn' and T!='yourturn':
k=input()
client.sendto(k.encode('utf-8'),('192.168.0.11', 20105))
if k=='yourturn':
T='yourturn'
continue
I'm trying to send a large file (.avi) over socket by sending the content of the file in chunks (a little bit like torrents). The problem is that the script doesn't send the file. I'm out of ideas here.
Any help or twerking of the script would be very appreciated.
Server:
import socket
HOST = ""
PORT = 8050
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
conn, addr = sock.accept()
print("Connected by ", str(addr))
while 1:
data = conn.recv(1024)
if data.decode("utf-8") == 'GET':
with open(downFile,'rb') as output:
l = output.read(1024)
while (l):
conn.send(l)
l = output.read(1024)
output.close()
conn.close()
Client:
import socket
HOST = "localhost"
PORT = 8050
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST,PORT))
while 1:
message = input()
sock.send(bytes(message,'UTF-8'))
conn.send(str.encode('GET'))
with open(downFile, 'wb+') as output:
while True:
rec = str(sock.recv(1024), "utf-8")
if not rec:
break
output.write(rec)
output.close()
print('Success!')
sock.close()
Here are a working client and server that should demonstrate transferring a file over a socket. I made some assumptions about what your code was supposed to do, for example, I assumed that the initial message the client sent to the server was supposed to be the name of the file to download.
The code also includes some additional functionality for the server to return an error message to the client. Before running the code, make sure the directory specified by DOWNLOAD_DIR exists.
Client:
import socket
import sys
import os
HOST = "localhost"
PORT = 8050
BUF_SIZE = 4096
DOWNLOAD_DIR = "downloads"
def download_file(s, down_file):
s.send(str.encode("GET\n" + down_file))
rec = s.recv(BUF_SIZE)
if not rec:
return "server closed connection"
if rec[:2].decode("utf-8") != 'OK':
return "server error: " + rec.decode("utf-8")
rec = rec[:2]
if DOWNLOAD_DIR:
down_file = os.path.join(DOWNLOAD_DIR, down_file)
with open(down_file, 'wb') as output:
if rec:
output.write(rec)
while True:
rec = s.recv(BUF_SIZE)
if not rec:
break
output.write(rec)
print('Success!')
return None
if DOWNLOAD_DIR and not os.path.isdir(DOWNLOAD_DIR):
print('no such directory "%s"' % (DOWNLOAD_DIR,), file=sys.stderr)
sys.exit(1)
while 1:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except Exception as e:
print("cannot connect to server:", e, file=sys.stderr)
break
file_name = input("\nFile to get: ")
if not file_name:
sock.close()
break
err = download_file(sock, file_name)
if err:
print(err, file=sys.stderr)
sock.close()
Server:
import socket
import sys
import os
HOST = ""
PORT = 8050
BUF_SIZE = 4096
def recv_dl_file(conn):
data = conn.recv(1024)
if not data:
print("Client finished")
return None, None
# Get command and filename
try:
cmd, down_file = data.decode("utf-8").split("\n")
except:
return None, "cannot parse client request"
if cmd != 'GET':
return None, "unknown command: " + cmd
print(cmd, down_file)
if not os.path.isfile(down_file):
return None, 'no such file "%s"'%(down_file,)
return down_file, None
def send_file(conn):
down_file, err = recv_dl_file(conn)
if err:
print(err, file=sys.stderr)
conn.send(bytes(err, 'utf-8'))
return True
if not down_file:
return False # client all done
# Tell client it is OK to receive file
sent = conn.send(bytes('OK', 'utf-8'))
total_sent = 0
with open(down_file,'rb') as output:
while True:
data = output.read(BUF_SIZE)
if not data:
break
conn.sendall(data)
total_sent += len(data)
print("finished sending", total_sent, "bytes")
return True
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(1)
keep_going = 1
while keep_going:
conn, addr = sock.accept()
print("Connected by", str(addr))
keep_going = send_file(conn)
conn.close() # close clien connection
print()
sock.close() # close listener
My question is that how to call server and client sequentially in main method ?
Problem is that python debugger waiting and be suck in line that calling the server(blocking the calling client line).
I tried threading but not work . Thanks for your attention.
IMPORTANT: Below codes using Python2
Main python file:
import xClient
import xServer
import threading
tempServer=xServer
tempClient=xClient
thrMain = threading.Thread(target=tempServer.innerClient.Main())
thrMain.start()
thrMain.join()
tempClient.innerClient.Main()
xClient.py : # STANDARD Client code and works correctly
import socket
import time
class innerClient:
def Main():
time.sleep(2)
host = '127.0.0.1'
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
message = "test message"
while True:
s.send(message.encode('ascii'))
data = s.recv(1024)
print('Received from the server :', str(data.decode('ascii')))
ans = raw_input('Continue(y/n) :')
if ans == 'y':
continue
else:
break
s.close()
xServer.py : # STANDARD Server code and works correctly
import socket
import threading
class innerServer:
print_lock = threading.Lock()
# thread fuction
def threaded(c):
while True:
data = c.recv(1024)
if not data:
print('See you later')
print_lock.release()
break
data = data[::-1]
c.send(data)
c.close()
def Main():
host = ""
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("socket binded to post", port)
s.listen(5)
print("socket is listening")
while True:
c, addr = s.accept()
print_lock.acquire()
print('Connected to :', addr[0], ':', addr[1])
thr = threading.Thread(target=threaded, args=(c,))
thr.start()
thr.join()
s.close()
TCP Socket Diagram
I'm new to python socket programming. I want to transfer 5 files (photos) from one host in mininet to another. The name of these files are numbered respectively (I mean 1.jpg, 2.jpg and ...). The problem is that when I run these codes, the first photo is transferred correctly but others become corrupted. What's the problem:
sender.py
import socket
import sys
buf = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.1',12345))
for i in range(1,6):
with open("%d.jpg" % (i),'rb') as f:
data = f.read(buf)
while 1:
if not data:
break
s.sendall(data)
data = f.read(buf)
s.close()
receiver.py:
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('10.0.0.1', 12345))
buf = 1024
s.listen(1)
conn , addr = s.accept()
for i in range(6,11):
with open("%d.jpg" % (i),'wb') as f:
while 1:
data = conn.recv(buf)
#print(data[:10])
#print "PACKAGE RECEIVED..."
f.write(data)
if not data: break
#conn.close()
#s.close()
The simple solution to your problem is to create a new connection for each file. The code below does that.
Sender
from __future__ import print_function
import socket
HOST = 'localhost'
PORT = 12345
BUFSIZE = 4096
def send_file(fname):
with open(fname, 'rb') as f:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except socket.error as err:
print(err, HOST, PORT)
sock.close()
return
while True:
data = f.read(BUFSIZE)
if not data:
break
while data:
sent = sock.send(data)
data = data[sent:]
sock.close()
fnames = [
'test0.jpg',
'test1.jpg',
'test2.jpg',
'test3.jpg',
]
def main():
for fname in fnames:
send_file(fname)
if __name__ == '__main__':
main()
Receiver
from __future__ import print_function
import socket
HOST = 'localhost'
PORT = 12345
BUFSIZE = 4096
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((HOST, PORT))
except socket.error as err:
print('Bind failed', err)
return
sock.listen(1)
print('Socket now listening at', HOST, PORT)
file_number = 0
try:
while True:
conn, addr = sock.accept()
print('Connected with', *addr)
fname = 'image%d.jpg' % file_number
with open(fname, 'wb') as f:
while True:
data = conn.recv(BUFSIZE)
if not data:
break
f.write(data)
conn.close()
print(fname, 'saved\n')
file_number += 1
# Hit Break / Ctrl-C to exit
except KeyboardInterrupt:
print('\nClosing')
sock.close()
if __name__ == '__main__':
main()
You need to hit CtrlC or Break (depending on your OS) to exit the receiver.
But using those numeric file names at the receiver isn't very satisfactory , so I decided to make it a little more complicated. :) In the following version we send the file name before the file data. That's slightly tricky because the receiver needs to separate the file name from the actual file data. If each socket.recv call corresponded to a socket.send call that would be easy, but that's not guaranteed to happen: the received bytes may be split differently from how they were sent. The receiver needs to buffer the bytes so it can break them up correctly. See the Socket Programming HOWTO for details.
So that the receiver knows where the file name ends we first send a single byte that encodes the length of the file name. A byte can hold a number from 0 to 255, so this code can't handle file names longer than that. After the length byte, we send the file name itself, encoded using UTF-8. And then we send the actual file contents.
The receiver uses a class named Receiver to handle the buffering. This class has a .get method which we can use to get a specified number of bytes. We use that method to get the file name length and the file name. And then we use Receiver's .save method to save the received file contents to a new file.
This code is a little bit messy because it's designed to run on Python 2 and Python 3, in any combination. It'd be somewhat neater if it was for Python 3 only. I hard-coded 'localhost' as the host name, since I only have one computer, so I couldn't test it over a network, but I'm confident that it will work correctly on a network.
Here's the sender:
from __future__ import print_function
import socket
from struct import pack
HOST = 'localhost'
PORT = 12345
BUFSIZE = 4096
def send(sock, data):
while data:
sent = sock.send(data)
data = data[sent:]
def send_file(fname):
with open(fname, 'rb') as f:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
except socket.error as err:
print(err, HOST, PORT)
sock.close()
return
# Send the file name length & the filename itself in one packet
send(sock, pack('B', len(fname)) + fname.encode())
while True:
data = f.read(BUFSIZE)
if not data:
break
send(sock, data)
sock.close()
fnames = [
'test1.gif',
'test2.jpg',
'test3.png',
'test4.pdf',
]
def main():
for fname in fnames:
send_file(fname)
if __name__ == '__main__':
main()
And here's the receiver:
from __future__ import print_function
import socket
from struct import unpack
HOST = 'localhost'
PORT = 12345
BUFSIZE = 4096
class Receiver:
''' Buffer binary data from socket conn '''
def __init__(self, conn):
self.conn = conn
self.buff = bytearray()
def get(self, size):
''' Get size bytes from the buffer, reading
from conn when necessary
'''
while len(self.buff) < size:
data = self.conn.recv(BUFSIZE)
if not data:
break
self.buff.extend(data)
# Extract the desired bytes
result = self.buff[:size]
# and remove them from the buffer
del self.buff[:size]
return bytes(result)
def save(self, fname):
''' Save the remaining bytes to file fname '''
with open(fname, 'wb') as f:
if self.buff:
f.write(bytes(self.buff))
while True:
data = self.conn.recv(BUFSIZE)
if not data:
break
f.write(data)
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((HOST, PORT))
except socket.error as err:
print('Bind failed', err)
return
sock.listen(1)
print('Socket now listening at', HOST, PORT)
try:
while True:
conn, addr = sock.accept()
print('Connected with', *addr)
# Create a buffer for this connection
receiver = Receiver(conn)
# Get the length of the file name
name_size = unpack('B', receiver.get(1))[0]
# Get the file name itself
name = receiver.get(name_size).decode()
print('name', name)
# Save the file
receiver.save(name)
conn.close()
print('saved\n')
# Hit Break / Ctrl-C to exit
except KeyboardInterrupt:
print('\nClosing')
sock.close()
if __name__ == '__main__':
main()
You should use it like:
with open("%d.jpg" % (i),'wb') as f:
while 1:
data = conn.recv(buf)
#print(data[:10])
#print "PACKAGE RECEIVED..."
f.write(data)
if not data: break
this way f gets closed automatically when you leave the with block when you exit the while.
I guess you need to extend the protocol so that the receiver knows what it gets and that you can let it act on that. Something like a 'begin-of-transfer' ... sending the filename, sending the data, sending 'end-of-transfer' that makes the receiver close the file
so right now in order to receive your message you need to receive one
my teachers instructions are (in the main)"Modify the loop so that it only listens for keyboard input and then sends it to the server."
I did the rest but don't understand this, ... help?
import socket
import select
import sys
import threading
'''
Purpose: Driver
parameters: none
returns: none
'''
def main():
host = 'localhost'
port = 5000
size = 1024
#open a socket to the client.
try:
clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSock.connect((host,port))
#exit on error
except socket.error, (value,message):
if clientSock :
clientSock.close()
print "Could not make connection: " + message
sys.exit(1)
thread1 = ClientThread()
thread1.start()
while True:
#wait for keyboard input
line = raw_input()
#send the input to the server unless its only a newline
if line != "\n":
clientSock.send(line)
#wait to get something from the server and print it
data = clientSock.recv(size)
print data
class ClientThread(threading.Thread):
'''
Purpose: the constructor
parameters: the already created and connected client socket
returns: none
'''
def __init__(self, clientSocket):
super(ClientThread, self).__init__()
self.clientSocket = clientSocket
self.stopped = False
def run(self):
while not self.stopped:
self.data = self.clientSocket.recv(1024)
print self.data
main()
I assume your purpose is to create a program that starts two threads, one (client thread) receives keyboard input and sends to the other (server thread), the server thread prints out everything it received.
Based on my assumption, you first need to start a ServerThread listen to a port (it's not like what your 'ClientThread' did). Here's an example:
import socket
import threading
def main():
host = 'localhost'
port = 5000
size = 1024
thread1 = ServerThread(host, port, size)
thread1.start()
#open a socket for client
try:
clientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSock.connect((host,port))
except socket.error, (value,message):
if clientSock:
clientSock.close()
print "Could not connect to server: " + message
sys.exit(1)
while True:
#wait for keyboard input
line = raw_input()
#send the input to the server unless its only a newline
if line != "\n":
clientSock.send(line)
# Is server supposed to send back any response?
#data = clientSock.recv(size)
#print data
if line == "Quit":
clientSock.close()
break
class ServerThread(threading.Thread):
def __init__(self, host, port, size):
super(ServerThread, self).__init__()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((host, port))
self.sock.listen(1)
self.data_size = size
self.stopped = False
def run(self):
conn, addr = self.sock.accept()
print 'Connected by', addr
while not self.stopped:
data = conn.recv(self.data_size)
if data == 'Quit':
print 'Client close the connection'
self.stopped = True
else:
print 'Server received data:', data
# Is server supposed to send back any response?
#conn.sendall('Server received data: ' + data)
conn.close()
if __name__ == '__main__':
main()
And these are the output:
Connected by ('127.0.0.1', 41153)
abc
Server received data: abc
def
Server received data: def
Quit
Client close the connection
You may check here for more details about Python socket: https://docs.python.org/2/library/socket.html?#example