#listen connecting
s.listen(10) #why we input 10, you can read manual about listen function
print('Socket now listening') Accept connection:
方法: socket_accpect用来接收请求。
HOST = '' #HOST name or IP address
PORT = 7001 #remote port
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print ('Socket created')
#bind ip/port
try:
s.bind((HOST,PORT))
except socket.error as msg:
print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print ('Socket bind complete')
#listen connecting
s.listen(10)
print('Socket now listening')
#simple way as server
#-------------------------------------------------------
#wait to accept a connection - blocking call
#conn, addr = s.accept()
##display client information
#print ('Connected with ' + addr[0] + ':' + str(addr[1]))
##now keep talking with the client
#data = conn.recv(1024)
#-------------------------------------------------------
#liver server, always running
#-------------------------------------------------------
#now keep talking with the client
#while 1:
# #wait to accept a connection - blocking call
# conn, addr = s.accept()
# print ('Connected with ' + addr[0] + ':' + str(addr[1]))
# data = conn.recv(1024)
# #reply = 'OK...' + data
# if not data:
# break
# conn.sendall(data)
# print(data)
##-------------------------------------------------------
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
#start_new_thread(clientthread ,(conn,))
threading._start_new_thread(clientthread ,(conn,))
#close and dispoiled socket
conn.close()
s.close()
输出结果:
server:
Client:
So,现在我们拥有了一个server,它是一个很棒的学你说话的机器人,HAHA
Conclusion:
截至目前,我相信你已经掌握了在Python中基础的socket网络编程,你可以尝试创建其他的社交客户端或与其相近的实例。至此,放学。不会再讲5分钟。
Bug fix:
开发环境: Python3.4 + ptvs
以上代码均已通过测试,当然不排除Python版本不一样的情况,实际上我也在原作者的基础上修改了很多,如果有bug的话,欢迎指正。