Answers for "python tcp example"

2

python tcp socket example

# Basic example where server accepts messages from client.

# importing socket library
import socket

# socket.AF_INET means we're using IPv4 ( IP version 4 )
# socket.SOCK_STREAM means we're using TCP protocol for data transfer
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
  
  # Binding socket to specified ip address and port
  socket.bind((ip, port))
  
  # This is max ammount of clients we will accept
  socket.listen(1)
  
  # Accepting connection from client
  sock, addr = socket.accept()
  print("Client connected from", addr)
  
  # Receiving data from client
  while True:
    data = sock.recv(16384) # Raw data from client
    text = data.decode('utf-8') # Decoding it
    
    print("Message from client:", text)
    
elif mode == "c":
  ip = input("Server ip address: ")
  
  # Connecting to server
  socket.connect((ip, 80))
  
  # Sending data
  while True:
    socket.send(input("Message: ").encode('utf-8'))
Posted by: Guest on May-14-2021
1

tcp python

#!/usr/bin/env python3

import socket

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 65432        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))
Posted by: Guest on June-09-2021
0

tcp python

conn, addr = s.accept()
with conn:
    print('Connected by', addr)
    while True:
        data = conn.recv(1024)
        if not data:
            break
        conn.sendall(data)
Posted by: Guest on June-09-2021
0

tcp python

import socket

HOST = '172.16.180.10'
PORT = 6789

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
print 'Connexion vers ' + HOST + ':' + str(PORT) + ' reussie.'

message = 'Hello, world'
print 'Envoi de :' + message
n = client.send(message)
if (n != len(message)):
        print 'Erreur envoi.'
else:
        print 'Envoi ok.'

print 'Reception...'
donnees = client.recv(1024)
print 'Recu :', donnees

print 'Deconnexion.'
client.close()
Posted by: Guest on August-18-2021

Python Answers by Framework

Browse Popular Code Answers by Language