1import socket
2TCP_IP = '127.0.0.1'
3TCP_PORT = 5005
4BUFFER_SIZE = 1024
5MESSAGE = "Hello, World!"
6s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
7s.connect((TCP_IP, TCP_PORT))
8s.send(MESSAGE)
9data = s.recv(BUFFER_SIZE)
10s.close()
11print "received data:", data
1#!/usr/bin/env python3
2
3import socket
4
5HOST = '127.0.0.1' # Standard loopback interface address (localhost)
6PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
7
8with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
9 s.bind((HOST, PORT))
10 s.listen()
11 conn, addr = s.accept()
12 with conn:
13 print('Connected by', addr)
14 while True:
15 data = conn.recv(1024)
16 if not data:
17 break
18 conn.sendall(data)
19
1#!/usr/bin/env python3
2
3import socket
4
5HOST = '127.0.0.1' # The server's hostname or IP address
6PORT = 65432 # The port used by the server
7
8with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
9 s.connect((HOST, PORT))
10 s.sendall(b'Hello, world')
11 data = s.recv(1024)
12
13print('Received', repr(data))
14
1#!/usr/bin/python # This is server.py file
2
3import socket # Import socket module
4
5s = socket.socket() # Create a socket object
6host = socket.gethostname() # Get local machine name
7port = 12345 # Reserve a port for your service.
8s.bind((host, port)) # Bind to the port
9
10s.listen(5) # Now wait for client connection.
11while True:
12 c, addr = s.accept() # Establish connection with client.
13 print 'Got connection from', addr
14 c.send('Thank you for connecting')
15 c.close() # Close the connection
1import socket
2
3HOST = '127.0.0.1' # Standard loopback interface address (localhost)
4PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
5
6with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
7 s.bind((HOST, PORT))
8 s.listen()
9 conn, addr = s.accept()
10 with conn:
11 print('Connected by', addr)
12 while True:
13 data = conn.recv(1024)
14 if not data:
15 break
16 conn.sendall(data)