1import socket
2import sys
3HOST = ''
4PORT = 9000
5s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6print 'Socket created'
7try:
8 s.bind((HOST, PORT))
9except socket.error , msg:
10 print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
11 sys.exit()
12print 'Socket bind complete'
13s.listen(10)
14print 'Socket now listening'
15conn, addr = s.accept()
16print 'Connecting from: ' + addr[0] + ':' + str(addr[1])
17while 1:
18 message=raw_input(">")
19 s.sendto(message, (addr[0], addr[1]))
20 print(s.recv(1024))
21
1# text_send_server.py
2
3import socket
4import select
5import time
6
7HOST = 'localhost'
8PORT = 65439
9
10ACK_TEXT = 'text_received'
11
12
13def main():
14 # instantiate a socket object
15 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
16 print('socket instantiated')
17
18 # bind the socket
19 sock.bind((HOST, PORT))
20 print('socket binded')
21
22 # start the socket listening
23 sock.listen()
24 print('socket now listening')
25
26 # accept the socket response from the client, and get the connection object
27 conn, addr = sock.accept() # Note: execution waits here until the client calls sock.connect()
28 print('socket accepted, got connection object')
29
30 myCounter = 0
31 while True:
32 message = 'message ' + str(myCounter)
33 print('sending: ' + message)
34 sendTextViaSocket(message, conn)
35 myCounter += 1
36 time.sleep(1)
37 # end while
38# end function
39
40def sendTextViaSocket(message, sock):
41 # encode the text message
42 encodedMessage = bytes(message, 'utf-8')
43
44 # send the data via the socket to the server
45 sock.sendall(encodedMessage)
46
47 # receive acknowledgment from the server
48 encodedAckText = sock.recv(1024)
49 ackText = encodedAckText.decode('utf-8')
50
51 # log if acknowledgment was successful
52 if ackText == ACK_TEXT:
53 print('server acknowledged reception of text')
54 else:
55 print('error: server has sent back ' + ackText)
56 # end if
57# end function
58
59if __name__ == '__main__':
60 main()
61