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)
1import socket
2import threading
3
4HOST = '127.0.0.1'
5PORT = 9090
6
7class Client:
8 def __init__(self, host, port):
9 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
10 self.sock.connect((host, port))
11
12 receive_thread = threading.Thread(target=self.receive)
13 receive_thread.start()
14
15 def write(self, message):
16 message = message.encode('utf-8')
17 self.sock.send(message)
18
19 def stop(self):
20 self.sock.close()
21
22 def receive(self):
23 while True:
24 try:
25 message = self.sock.recv(1024).decode('utf-8')
26 print(message)
27 except ConnectionAbortedError:
28 break
29 except:
30 print("Error")
31 self.socket.close()
32
33client = Client(HOST, PORT)