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”,我得到了回复,连接被终止。