Python客户端无法接收从Python Server发送的数据

时间:2016-07-26 12:48:41

标签: python-2.7 sockets server client

我正在尝试将一些数据从我的python客户端发送到python服务器 我已经按照link

进行了操作

我的python客户端代码如下

#Socket client example in python

import socket   #for sockets
import sys  #for exit

#create an INET, STREAMing socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
    print 'Failed to create socket'
    sys.exit()

print 'Socket Created'

host = '10.4.1.25';
port = 80;

try:
    remote_ip = socket.gethostbyname( host )

except socket.gaierror:
    #could not resolve
    print 'Hostname could not be resolved. Exiting'
    sys.exit()

#Connect to remote server
s.connect((host , port))

print 'Socket Connected to ' + host + ' on ip ' + remote_ip

message = "16973"

try :
    #Set the whole string
    s.sendall(message)
except socket.error:
    #Send failed
    print 'Send failed'
    sys.exit()

print 'Message send successfully'

#Now receive data
reply = s.recv(4096)

print reply 

python服务器代码是

import socket
import sys

HOST = ''   # Symbolic name meaning all available interfaces
PORT = 80 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

s.listen(10)
print 'Socket now listening'

#wait to accept a connection - blocking call
conn, addr = s.accept()

print 'Connected with ' + addr[0] + ':' + str(addr[1])

#now keep talking with the client
data = conn.recv(1024)
conn.sendall(data)

conn.close()
s.close()

函数sendall用于向客户端发送数据,这意味着当我在服务器上的终端输入文本时,我也应该在客户端上看到它。但这不会发生

我得到的输出是

服务器输出

$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 10.4.1.255:44656 

客户端输出

$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

我无法知道这里出了什么问题?

另外,我如何从Python客户端向Python服务器发送数据(消息)?

任何帮助都会很棒! 谢谢!

0 个答案:

没有答案