Example 1: send data through tcp sockets python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print "received data:", data
Example 2: socket programming in python
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
Example 3: client server python socket
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()
Example 4: python tcp socket example
import socket
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Choose mode. s - server, c - client")
mode = input("> ")
if mode == "s":
ip = input("Your computer's ip address: ")
port = 80
socket.bind((ip, port))
socket.listen(1)
sock, addr = socket.accept()
print("Client connected from", addr)
while True:
data = sock.recv(16384)
text = data.decode('utf-8')
print("Message from client:", text)
elif mode == "c":
ip = input("Server ip address: ")
socket.connect((ip, 80))
while True:
socket.send(input("Message: ").encode('utf-8'))
Example 5: python socket
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
Example 6: socket python functions
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)