-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocketExchange.py
66 lines (60 loc) · 2.12 KB
/
socketExchange.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/python
"""
@Author Brett
Sends string to server, and waits for reply back.
If valid, returns sock.recv(buf), else returns None.
"""
import socket # Import socket module
import sys
def main():
launchDummyServer()
#
SOCKETHOST = 'localhost'
SOCKETPORT = 12345
SOCKET = (SOCKETHOST, SOCKETPORT)
snd_msg = 'from function to server'
print snd_msg
rec_msg = socketExchange(snd_msg, SOCKET, DEBUG=True)
print rec_msg
def socketExchange(msg, SOCKET, buf=1024, DEBUG=False):
try:
SOCKETHOST, SOCKETPORT = SOCKET
print 'Sending Data To: ', SOCKET
sock = socket.socket(socket.AF_INET)
sock.connect((SOCKETHOST, SOCKETPORT))
val = sock.send(msg)
if DEBUG: print 'From: ' + 'Client (me)' + ', Data: ' + str([msg])
ret = sock.recv(buf)
if DEBUG: print 'From: ' + str((SOCKETHOST, SOCKETPORT)) + ', Data: ' + str([ret])
sock.close()
if DEBUG: print 'Closed: Server on ' + str((SOCKETHOST, SOCKETPORT))
except:
print 'Data Failed...'
return None
return ret
def launchDummyServer():
import thread
thread.start_new_thread(server, ())
def server():
import socket
H = 'localhost'
P = 12345
SERVERRESPONSE = 'hello client, said the server.'
sock = socket.socket()
sock.bind((H, P))
print ['(SOCKETHOST, SOCKETPORT)', (H, P)]
sock.listen(5)
while True:
socket_connection, addr = sock.accept()
client_msg_str = socket_connection.recv(1024)
if client_msg_str:
print 'From: ' + str(addr) + ', Data: ' + str([client_msg_str])
socket_connection.send(SERVERRESPONSE)
print 'From: ' + 'Server (me)' + ', ' + 'Data: ' + str([SERVERRESPONSE])
socket_connection.close()
print 'Closed: ' + 'Client on ' + str(addr)
break
socket_connection.close()
print 'Closed: ' + 'Client on ' + str(addr)
if __name__ == '__main__':
main()