Python网络编程(Sockets)

一个简单的服务器

#!/usr/bin/python3           # This is server.py file
import socket

# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name
host = socket.gethostname()                           

port = 8088

# bind to the port
serversocket.bind((host, port))                                  
print("Server start at port: 8088")
# queue up to 5 requests
serversocket.listen(5)                                           

while True:
    # establish a connection
    clientsocket,addr = serversocket.accept()      

    print("Got a connection from %s" % str(addr))

    msg='Thank you for connecting'+ "
"
    clientsocket.send(msg.encode('ascii'))
    clientsocket.close()

一个简单的客户端

#!/usr/bin/python3           # This is client.py file

import socket

# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# get local machine name
host = socket.gethostname()

port = 8088

# connection to hostname on the port.
s.connect((host, port))

# Receive no more than 1024 bytes
msg = s.recv(1024)

s.close()

print (msg.decode('ascii'))

原文地址:https://www.cnblogs.com/sea-stream/p/10181097.html