Python socket network programming, pythonsocket
import socketclim=socket.socket()clim.connect(("localhost",6969))while True: thing=input(">>>>") clim.send(thing.encode("utf-8")) date = clim.recv(1024) print("reac:",date)clim.close()
Import socketserver = socket. socket () server. bind ("localhost", 6968) server. listen () while True: conn, addr = server. accept () while True: data = conn. recv (1024) print (data) msg = input ("to the other Party:") # server. send (msg. encode ("UTF-8") # conn. send (msg. encode ("UTF-8") # Although server is the socket corresponding to the server, it does not actually connect any end, so server is used. recv will cause an error. # because the socket object of the server only has the specified port specified by listen, the socket that can be connected is server. socket returned after accept () #, which is the Socket connected to the specified port on the server, so it can be used for communicationCase 2: transfer files
Import socketclim = socket. socket () clim. connect ("localhost", 6969) f = open ("registration code .txt", "wb") while True: thing = input (">>>>") clim. send (thing. encode ("UTF-8") date = clim. recv (1024) print ("reac:", date) f. write (date) f. flush () clim. close ()
Import socketimport osserver = socket. socket () server. bind ("localhost", 6969) server. listen () while True: conn, addr = server. accept () while True: data = conn. recv (1024) print (data) # OS. popen (data) f = open ("D: \ BaiduNetdiskDownload \ python \ pycharm2017.x Professional Edition registration code .txt") # server. send (msg. encode ("UTF-8") data = f. read () conn. send (data. encode ("UTF-8 "))Case 3: perform system operations on the server
import socketclient=socket.socket()client.connect(("localhost",6969))while True: thing=input(">>>>") client.send(thing.encode("utf-8")) date = client.recv(1024) print("reac:",date)clim.close()
Import socketimport osserver = socket. socket () server. bind ("localhost", 6969) server. listen () while True: conn, addr = server. accept () while True: data = conn. recv (1024) print (data) res = OS. popen (data) # OS. popen (command [, mode [, bufsize]) executes the system command and writes the execution result to a temporary file. The returned value is the object of the opened file. The default mode is r, that is, the file is opened in read-only mode by default; # buffersize is the system buffer size by default (buffer, this concept applies to disk write data; cache, this concept applies to disk read data ). # Since the returned object is a file object, we can understand that OS. popen (). read () is to read the content of this file object. # The returned value is the content of the file. Conn. send (res)