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####### TCP Server #######
2
3from socket import AF_INET,SOCK_STREAM,socket
4
5# AF_INET => TCP
6# SOCK_STREAM => IPv4
7
8sobj = socket(AF_INET,SOCK_STREAM)
9sobj.bind(('127.0.0.1',12345))
10sobj.listen(1)
11
12client , addr = sobj.accept()
13print("the ip is connected to server ",addr)
14
15while(True):
16
17 message = input()
18 if(message == "exit"):
19 client.close()
20 break
21 else:
22 client.send(message.encode())
23
24
25####### TCP Client #######
26
27from socket import AF_INET,SOCK_STREAM,socket
28
29sobj = socket(AF_INET,SOCK_STREAM)
30sobj.connect(('127.0.0.1',12345))
31while True:
32 message = sobj.recv(2048)
33 if(message == "exit"):
34 sobj.close()
35 break
36 elif(message.decode() == ''):
37 pass
38 else:
39 print(message.decode())
40
41
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
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)
1conn, addr = s.accept()
2with conn:
3 print('Connected by', addr)
4 while True:
5 data = conn.recv(1024)
6 if not data:
7 break
8 conn.sendall(data)
9
1import socket
2
3HOST = '172.16.180.10'
4PORT = 6789
5
6client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
7client.connect((HOST, PORT))
8print 'Connexion vers ' + HOST + ':' + str(PORT) + ' reussie.'
9
10message = 'Hello, world'
11print 'Envoi de :' + message
12n = client.send(message)
13if (n != len(message)):
14 print 'Erreur envoi.'
15else:
16 print 'Envoi ok.'
17
18print 'Reception...'
19donnees = client.recv(1024)
20print 'Recu :', donnees
21
22print 'Deconnexion.'
23client.close()
24