Answers for "use tcp in python"

1

python tcp server

####### TCP Server #######

from socket import AF_INET,SOCK_STREAM,socket

# AF_INET => TCP
# SOCK_STREAM => IPv4

sobj = socket(AF_INET,SOCK_STREAM)
sobj.bind(('127.0.0.1',12345))
sobj.listen(1)

client , addr = sobj.accept()
print("the ip is connected to server ",addr)

while(True):
    
    message = input()
    if(message == "exit"):
        client.close()
        break
    else:
        client.send(message.encode())

        
####### TCP Client #######

from socket import AF_INET,SOCK_STREAM,socket

sobj = socket(AF_INET,SOCK_STREAM)
sobj.connect(('127.0.0.1',12345))
while True:
    message = sobj.recv(2048)
    if(message == "exit"):
        sobj.close()
        break
    elif(message.decode() == ''):
        pass
    else:
        print(message.decode())
Posted by: Guest on August-25-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