1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import
SocketServer #导入SocketServer,多线程并发由此类实现
class
MySockServer(SocketServer.BaseRequestHandler): #定义一个类
def handle(self): #handle(self)方法是必须要定义的,可以看上面的说明
print
'Got a new connection from'
, self.client_address
while
True:
data = self.request.recv(
1024
) #需要通过self的方法调用数据接收函数
if
not data:
break
print
'recv:'
, data
self.request.send(data.upper()) #需要通过self的方法调用数据接收函数
if
__name__ ==
'__main__'
: #并非一定要用这样的方式,只是建议这样使用
HOST =
''
#定义侦听本地地址口(多个IP地址情况下),这里表示侦听所有
PORT =
50007
#Server端开放的服务端口
s = SocketServer.ThreadingTCPServer((HOST, PORT), MySockServer)
#调用SocketServer模块的多线程并发函数
s.serve_forever() #持续接受客户端的连接
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
socket
HOST =
'192.168.1.13'
PORT =
50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while
True:
user_input = raw_input(
'msg to send:'
).strip()
s.sendall(user_input)
data = s.recv(
1024
)
print
'Received'
, repr(data)
s.close()
|
1
2
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python Thread_socket_server4.py
===>光标在此处处于等待状态
|
1
2
3
4
5
6
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python client4.py
msg to send:Hello! ===>User输入数据
Received
'HELLO!'
===>Server端返回的数据
msg to send:I'm Client A.
Received
"I'M CLIENT A."
msg to send: ===>继续等待User输入数据
|
1
2
3
4
5
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python Thread_socket_server4.py
Got a
new
connection from (
'192.168.1.13'
,
52650
)
recv: Hello!
recv: I'm Client A. ===>接收到Client A端发送的数据
===>光标在此处处于等待状态
|
1
2
3
4
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python client4.py
msg to send:I'm Client B. ===>User输入数据
Received
"I'M CLIENT B."
===>Server端返回的数据
msg to send: ===>继续等待User输入数据
|
1
2
3
4
5
6
7
|
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day5$ python Thread_socket_server4.py
Got a
new
connection from (
'192.168.1.13'
,
52650
)
recv: Hello!
recv: I'm Client A.
Got a
new
connection from (
'192.168.1.13'
,
52651
)
recv: I'm Client B. ===>接收到Client A端发送的数据
===>光标在此处处于等待状态
|