Created
November 8, 2015 03:35
-
-
Save Teino1978-Corp/f2216f73f1333965b37c to your computer and use it in GitHub Desktop.
Basic socket communication in Python
This file contains hidden or 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 | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| host = socket.gethostname() | |
| port = 4560 | |
| # Binds the server to address and port. | |
| s.bind((host, port)) | |
| # Listens for a max of 5 clients. | |
| s.listen(5) | |
| while True: | |
| # Accepts a connection. | |
| c, addr = s.accept() | |
| print('Recieved connection from', addr) | |
| # Receives data from the client. | |
| data = c.recv(4096).decode('utf8') | |
| # Responds with a 'PONG'. | |
| if data == 'PING': | |
| print('<', data) | |
| c.send(bytes('PONG', 'utf8')) | |
| print('>', 'PONG') | |
| # Closes the connection. | |
| c.close() |
This file contains hidden or 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 | |
| s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| host = socket.gethostname() | |
| port = 4560 | |
| # Connects to the server. | |
| s.connect((host, port)) | |
| print('Connected.') | |
| # Initiates the conversation. | |
| s.send(bytes('PING', 'utf8')) | |
| print('>', 'PING') | |
| # Loop to listen for incoming data. | |
| while True: | |
| try: | |
| data = s.recv(4096).decode('utf8') | |
| # Quits if it receives 'PONG'. | |
| if data == 'PONG': | |
| print('<', data) | |
| break | |
| except socket.error: | |
| print('Socket died.') | |
| raise | |
| except socket.timeout: | |
| print('Socket timeout.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment