网络基础——阿里云部署 ---连外网实现远程通信

#server

# coding:utf-8 #在python2中必须加文件头
# from socket import *
#
#
# server=socket(AF_INET,SOCK_STREAM)
# server.bind(('127.0.0.1',8080))
# server.listen(5)
#
# while True:
#     conn,addr=server.accept()
#     print(addr)
#
#     while True:
#         try:
#             data=conn.recv(1024)
#             if len(data) == 0:break
#             conn.send(data.upper())
#         except Exception:
#             break
#
#     conn.close()

# 支持并发版本
import socketserver


class MyRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):  # 处理通信
        print(self.client_address)
        while True:
            try:
                data = self.request.recv(1024)  # self.request=>conn
                if len(data) == 0: break
                self.request.send(data.upper())
            except Exception:
                break
        self.request.close()


if __name__ == '__main__':
    s = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyRequestHandler, bind_and_activate=True)
    s.serve_forever()

 

#client

from socket import *

client=socket(AF_INET,SOCK_STREAM)
client.connect(('121.199.45.113',8080))

while True:
    msg=input(">>: ").strip()
    if len(msg) == 0:
        continue

    client.send(msg.encode('utf-8'))
    data=client.recv(1024)
    print(data.decode('utf-8'))