TCP Client
import socket target_host = "192.168.1.104" target_port = 9999 #创建一个socket对象 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #连接服务器 client.connect((target_host,target_port)) #发送一些数据 say = "I am a client" client.send(bytes(say,encoding='gbk')) #接收一些数据 response = client.recv(4096) print(response)
TCP Server
import socket import threading #客户处理线程 def handle_client(client_socket): #打印客户端发送得到内容 request = client_socket.recv(1024) print ("[*] Received: %s" % request) #返还一个数据包 ''' 在Python3以后,字符串和bytes类型彻底分开了。字符串是以字符为单位进行处理的,bytes类型是以字节为单位处理的。 ''' say = "I am a server!!!" client_socket.send(bytes(say, encoding='gbk')) client_socket.close() def main(): bind_ip = "192.168.1.104" bind_port = 9999 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)) while True: client, addr = server.accept() # 挂起客户端线程,处理传入的数据 client_handler = threading.Thread(target=handle_client, args=(client,)) client_handler.start() if __name__ == "__main__": main()