python - socket 基础

空扰寡人 提交于 2020-01-19 03:44:43

 

最基本的socket实例:

Server端

import socket
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.bind(('127.0.0.1',8080))
phone.listen(2)
print ('Start Server: ')
connect,address = phone.accept()
msg = connect.recv(1024)
print ('客户端发来的消息是:',msg)
connect.send(msg.upper())
connect.close()
phone.close()

 

Client端

import socket
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080))
phone.send('test message!'.encode('utf-8'))
msg = phone.recv(1024)
print ('服务端发来的消息是:',msg)
phone.close()

 

Server端改进版

# -*-coding:utf-8-*-
__author__ = 'qikang'

import socket
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.bind(('127.0.0.1',8080))
phone.listen(5)

while True:
    print ('Start Server: ')
    connect,address = phone.accept()
    while True:
        # try:
        msg = connect.recv(1024)
        if not msg: break
        print ('客户端发来的消息是:',msg)
        connect.send(msg.upper())
        # except Exception as e:
        #     break
    connect.close()
phone.close()

 

Client端改进版

# -*-coding:utf-8-*-
__author__ = 'qikang'
import socket
phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080))
while True:
    input_str = input('请输入需要发送的代码:')
    phone.send(input_str.encode('utf-8'))
    msg = phone.recv(1024)
    print ('服务端发来的消息是:',msg)
phone.close()

 

 一个SSH Server和Client示例:

# -*-coding:utf-8-*-
import socket
import subprocess
import struct
from functools import partial

ip_port = ('127.0.0.1',8080)
buffer_size = 1024
back_log = 5


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

# 解决ip地址正在使用的问题
tcp_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

tcp_server.bind(ip_port)
tcp_server.listen(back_log)

print ('Running Server ...')
while True:
    connect,address = tcp_server.accept()
    print ('New Client: ',connect,address)
    while True:
        try:
            recv_cmd = connect.recv(buffer_size)
            print ('客户端发来的命令是:',recv_cmd )
            if not recv_cmd:
                break

            cmd = recv_cmd.decode('utf-8')
            cmd_result = subprocess.Popen(cmd,
                                          shell=True,
                                          stdin=subprocess.PIPE,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE
            )
            # cmd_result_stdin = cmd_result.stdin.read()
            cmd_result_stdout = cmd_result.stdout.read()
            cmd_result_stderr = cmd_result.stderr.read()

            # .encode('utf-8')
            if cmd_result_stderr:
                cmd_result_recv = cmd_result_stderr

            elif not cmd_result_stdout:
                cmd_result_recv = b'None'
            else:
                cmd_result_recv = cmd_result_stdout

            length_data = struct.pack('i',len(cmd_result_recv))

            # send length data.
            connect.send(length_data)

            client_ready = connect.recv(buffer_size)
            if client_ready == b'client_ready':
                connect.send(cmd_result_recv)

        except Exception as e:
            break
    connect.close()
tcp_server.close()
server 端

 

# -*-coding:utf-8-*-
import socket
import struct
from functools import partial

ip_port = ('127.0.0.1',8080)
buffer_size = 1024

tcp_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp_client.connect(ip_port)

while True:
    input_str = input('请输入需要执行的命令:')

    if input_str == 'quit' or input_str == 'q' or input_str == 'exit':
        break

    if not input_str:
        continue

    tcp_client.send(input_str.encode('utf-8'))

    # recv data length.
    data_length_recv = tcp_client.recv(buffer_size)
    data_length = struct.unpack('i',data_length_recv)[0]
    tcp_client.send(b'client_ready')

    recv_size = 0
    server_send_data = b''
    while data_length > recv_size:
        server_send_data += tcp_client.recv(buffer_size)
        recv_size = len(server_send_data)

    # windows gbk
    print (server_send_data.decode('gbk'))

    # linux utf-8
    # print (server_send_data.decode('utf-8'))

tcp_client.close()
client端

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!