lessons period 2
This commit is contained in:
38
period_2/02-sockets/902/SocketUtil.py
Normal file
38
period_2/02-sockets/902/SocketUtil.py
Normal file
@@ -0,0 +1,38 @@
|
||||
import socket
|
||||
import pickle
|
||||
import select
|
||||
|
||||
TCP_PORT = 5050
|
||||
BUFFER_SIZE = 1024
|
||||
|
||||
|
||||
def newServerSocket(ip_addr):
|
||||
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
server_socket.bind((ip_addr, TCP_PORT))
|
||||
server_socket.listen()
|
||||
return server_socket
|
||||
|
||||
|
||||
def recvObj(socket):
|
||||
ready_to_read, ready_to_write, in_error = select.select([socket], [], [socket], 20)
|
||||
if socket in ready_to_read:
|
||||
print('Server is ready to receive data ...')
|
||||
connected_socket, addr = socket.accept()
|
||||
print('Server is receiving data ...')
|
||||
all_data = b''
|
||||
while True:
|
||||
data = connected_socket.recv(BUFFER_SIZE)
|
||||
if not data:
|
||||
break
|
||||
all_data = all_data + data
|
||||
return pickle.loads(all_data)
|
||||
return None
|
||||
|
||||
|
||||
def sendObj(ip_addr, obj):
|
||||
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
soc.connect((ip_addr, TCP_PORT))
|
||||
data = pickle.dumps(obj)
|
||||
soc.send(data)
|
||||
soc.close()
|
||||
return False
|
Reference in New Issue
Block a user