2016-05-14 164 views
3

我正在讀取2.7.10客戶端和服務器中的2個程序。我如何修改這些程序以便從客戶端發送消息到服務器?如何發送郵件從客戶端到服務器在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 

回答

5

TCP套接字是雙向的。因此,連接後,有服務器和客戶端之間沒有什麼區別,你只需要一個流的末端:

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 

和客戶端:

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 
相關問題