临时端口:
node2:/root#cat /proc/sys/net/ipv4/ip_local_port_range
9000 65000
来看 bind 调用的例子,故意注释掉端口的赋值,完整的代码如下。
Last login: Tue Mar 24 02:02:34 2020 from 192.168.137.1
node1:/root#ps -ef | grep test
root 3957 3911 0 02:06 pts/3 00:00:00 python test.py
root 3992 3962 0 02:06 pts/4 00:00:00 grep test
node1:/root#netstat -nap | grep 3957
tcp 0 0 192.168.137.2:39191 0.0.0.0:* LISTEN 3957/python
node1:/root#
node1:/root/test#cat test.py
# coding = utf-8
# -*- coding:utf-8 -*-
import socket
ip_port = ('192.168.137.2',0)
BUFSIZE = 10
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)#创建套接字
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(ip_port)#绑定地址
s.listen(5)#监听链接
print('server listening8080...')
while True: #无限等待连接
conn,addr = s.accept() #接受客户端连接
print '1111111111111'
print(conn)
print '1111111111111'
print '2222222222222'
print(addr)
print '2222222222222'
print('接到来自%s的链接'%addr[0])
while True: #通信循环,无限接受客户端信息
msg = conn.recv(BUFSIZE) #接受消息的内容
if len(msg)==0:break #如果 不加,已连接的客户端突然断开,recv不再阻塞,发生死循环
print msg
print(msg.decode('utf8'),type(msg))
s.close()
#conn.send(msg.upper())#服务端发送消息
conn.close()#关闭链接
s.close()#关闭套接字