最近开始接触python网络方面的编程,同时也在恶补python…
于是顺手模仿书上写了一下TCP的客户端和服务端.

TCP客户端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import socket

target_host = "127.0.0.1"
target_port = 80

#建立一个socket对象
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#连接客户端
client.connect((target_host,target_port))

#发送一些数据
client.send("Successful!")

#接受一些数据
response=client.recv(4096)

print response

TCP服务端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import socket
import threading

bind_ip= "127.0.0.1"
bind_port= 80

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server.bind((bind_ip,bind_port))

server.listen(5)

print "[*] Listening on %s:%d" % (bind_ip,bind_port)

#这是客户端处理线程
def handle_client(client_socket):
#打印出客户端发送得到的内容
request = client_socket.recv(1024)

print "[*] Received: %s" % request

#返还一个数据包
client_socket.send("ACK!")
client_socket.close()

while True:
client,addr = server.accept()

print "[*] Accepted connection from: %s%d" % (addr[0],addr[1])

#挂起客户端线程,处理传入的数据
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()

结果:

1
2
3
4
5
6
服务端:
[*] Listening on 127.0.0.1:80
[*] Accepted connection from: 127.0.0.122666
[*] Received: Successful!
客户端:
ACK!