0
import socket
import sys

host=''  # Symbolic name meaning all available interfaces
port=7777  #random port

#creating socket
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "socket created"

#binding
try:
    sock.bind((host,port))
except socket.error,msg:
    print "Bind failed,Error no:"+str(msg[0])+"error:-"+str(msg[1])
    sys.exit()
print "Bind successful"

sock.listen(10)
print "Listening" # it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected.
conn, addr=sock.accept()#accept new connection
print "connected to "+str(addr[0])+":"+str(addr[1])

#receive from client
data=conn.recv(1024)
print "received-"+data
conn.sendall(data*2)

#terminate
conn.close()
sock.close()

以上是从客户端接收数据并回复的代码。我使用带有“telnet localhost 7777”的cmd进行连接。然后我想发送一个简单的“hello world”消息,但我只是输入了“h”,我得到了回复,连接被终止。

my_code.py 输出

4

1 回答 1

0

它对我有用。你的 socketClient 工作正常吗?

import socket
string='hello world'
print type(string)
HOST, PORT = 'localhost', 7777
# SOCK_STREAM == a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#sock.setblocking(0)  # optional non-blocking
sock.connect((HOST, PORT))
sock.send(string)
reply = sock.recv(1024)  # limit reply to 16K
print(reply)
sock.close()
return reply
于 2016-06-25T13:45:45.320 回答