|
事例1:
服务端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| #!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: phpergao
@license: Apache Licence
@file: socket_server.py
@time: 2016-05-22 19:22
"""
import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.bind(ip_port)
sk.listen(5)
while True:
print("server waiting")
conn,addr=sk.accept()
client_data=conn.recv(1024)
print(str(client_data,encoding="utf-8"))
conn.sendall(bytes("不要回答,我不想被占领",encoding="utf-8"))
conn.close()
|
客户端:
1
2
3
4
5
6
7
8
9
10
| import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.connect(ip_port)
sk.sendall(bytes("请求占领地球",encoding="utf-8"))
sk.sendall(bytes("\n我要开始侵略占领地球了",encoding="utf-8"))
server_reply=sk.recv(1024)
print(str(server_reply,encoding="utf-8"))
sk.close()
|
事例2:
服务端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.bind(ip_port)
sk.listen(5)
while True:
print("server waiting")
conn,addr=sk.accept()
client_data=conn.recv(1024)
print(str(client_data,encoding="utf-8"))
conn.sendall(bytes("不要回答,我不想被占领",encoding="utf-8"))
while True:
try:
client_data=conn.recv(1024)
print(str(client_data,encoding="utf-8"))
except Exception:
print("client close.")
break
conn.send(client_data)
conn.close()
|
客户端:
1
2
3
4
5
6
7
8
9
10
11
12
13
| import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.connect(ip_port)
sk.sendall(bytes("请求占领地球",encoding="utf-8"))
sk.sendall(bytes("\n我要开始侵略占领地球了",encoding="utf-8"))
server_reply=sk.recv(1024)
print(str(server_reply,encoding="utf-8"))
while True:
enter=input("enter:")
sk.send(bytes(enter,encoding="utf-8"))
sk.close()
|
在Linux服务端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.bind(ip_port)
sk.listen(5)
while True:
print("server waiting")
conn,addr=sk.accept()
client_data=conn.recv(1024)
print(str(client_data,encoding="utf-8"))
conn.sendall(bytes("不要回答,我不想被占领",encoding="utf-8"))
while True:
client_data=conn.recv(1024)
print(str(client_data,encoding="utf-8"))
if not client_data:
break
conn.send(client_data)
conn.close()
|
|
|