2016-05-14 11 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 
ので、接続後、サーバとクライアントの間に違いはありません、あなただけのストリームの端に持っています
関連する問題