2016-05-14 4 views
3

Ich lese 2 Programme in 2.7.10 mit Client und Server. Wie kann ich diese Programme ändern, um eine Nachricht vom Client zum Server zu senden?Wie schicke ich eine Nachricht vom Client zum Server in Python

#!/usr/bin/python   # This is server.py file 

import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
host = socket.gethostname() # Get local machine name 
port = 12345    # Reserve a port for your service. 
s.bind((host, port))  # Bind to the port 

s.listen(5)     # Now wait for client connection. 
while True: 
    c, addr = s.accept()  # Establish connection with client. 
    print 'Got connection from', addr 
    c.send('Thank you for connecting') 
    c.close()    # Close the connection 




#!/usr/bin/python   # This is client.py file 

import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
host = socket.gethostname() # Get local machine name 
port = 80    # Reserve a port for your service. 

s.connect((host, port)) 
print s.recv(1024) 
s.close      # Close the socket when done 

Antwort

5

TCP-Sockets sind bidirektional. So, nach dem Anschluss gibt es keinen Unterschied zwischen Server und Client ist, müssen Sie nur an den Enden eines Stroms:

import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
s.bind(('0.0.0.0', 12345))  # Bind to the port 

s.listen(5)     # Now wait for client connection. 
while True: 
    c, addr = s.accept()  # Establish connection with client. 
    print 'Got connection from', addr 
    print c.recv(1024) 
    c.close()    # Close the connection 

und den Kunden:

import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
s.connect(('localhost', 12345)) 
s.sendall('Here I am!') 
s.close()      # Close the socket when done 
Verwandte Themen