python服务器与Java基于socket通信

python服务端

 

# -- encoding:utf-8 --
"""
Greate by ibf on 2019
"""
import socket
import threading
import time
import re
import random

try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("create socket succ!")

    sock.bind(('192.168.0.104', 9999))
    print('bind socket succ!')

    sock.listen(5)
    print('listen succ!')

except:
    print("init socket error!")


def count_time(conn):
    global count
    global current_time
    try:
        while True:
            time.sleep(10)
            if (time.time() - current_time >= 30.0 and on_off == True) or (
                    time.time() - current_time >= 600.0 and on_off == True):
                mg = ('你好,是否继续保持连接:y/n\n', '你好,是否继续保持连接,收到请回答:y/n\n',
                      '你好,服务器将要断开与您的通信连接,是否继续保持连接:y/n\n', '连接已断开\n')
                conn.send(mg[count].encode('utf-8'))
                count += 1
                if count > 3:
                    conn.close()
                    return
    except BaseException:
        return


def thread_send(conn):
    global on_off
    try:
        conn.send('欢迎\n'.encode('utf-8'))
        greetings = ['你好,请问有什么需要帮助吗?', '很高兴为您服务。\n输入"python":进入python交互。\n输入"exit":退出交互。']
        while True:
            i = random.randint(0, 1)
            time.sleep(15)
            if time.time() - current_time < 30.0 and on_off:
                # msg = input('>>>').strip('\r\n')
                msg = greetings[i] + '\n'
                conn.send(msg.encode('utf-8'))
                # if msg == 'exit':
                #     conn.close()
    except BaseException:
        # print('异常断开连接')
        return


def pyhon365():
    global on_off, conn
    on_off = False
    nonius_location = 0

    def str_dispose(string):
        pt1 = re.compile(r'print\((.*?\)*)\)')
        pt1_str = pt1.sub(r'print(\1, file=result_file)', string)
        return re.sub(r'print\((.*,) *file *=[\w .]+(.*?\)*)\)', r'print(\1file=result_file\2)',
                      pt1_str)  # 确保file参数的值统一

    while not on_off:
        try:
            msg = conn.recv(1024).decode('utf-8').strip('\n')[2:] + '\n'
            if msg == 'exit\n':
                on_off = True
                conn.send('python已退出\n'.encode('utf-8'))
                break
            elif re.findall(r'.+?:\n', msg):
                num = 1
                while num >= 1:
                    conn.send(('...' + '    ' * num + '\n').encode('utf-8'))
                    statement = '{}'.format('    ' * num) + conn.recv(1024).decode('utf-8').strip('\n')[2:] + '\n'
                    if re.findall(r' +\n', statement):
                        num -= 1
                        continue
                    elif re.findall(r'.+?:\n', statement):
                        num += 1
                    msg += statement
            code_str = str_dispose(msg)
            try:
                exec('from CODERESOURCE import *\n' + code_str)
            except BaseException as e:
                conn.send((str(e) + '\n>>>\n').encode('utf-8'))
                continue
            result_file.seek(nonius_location)
            conn.send((result_file.read() + '>>>\n').encode('utf-8'))
            nonius_location = result_file.tell()
            src_file.write(code_str)
            src_file.flush()
        except BaseException:
            on_off = True
            src_file.close()
            result_file.close()
            return

if __name__ == '__main__':
    while True:
        print("listen for client...")
        conn, addr = sock.accept()
        print("get client")
        print(addr)
        current_time = time.time()
        count = 0
        on_off = True
        # conn.settimeout(30)
        t1 = threading.Thread(target=thread_send, args=(conn,))
        t2 = threading.Thread(target=count_time, args=(conn,))
        t1.setDaemon(True)
        t2.setDaemon(True)
        t1.start()
        t2.start()
        while True:
            try:
                str1 = conn.recv(1024).decode('utf-8')
                msg = str1.strip('\n')[2:]
                if msg:
                    count = 0
                    print('客户端发来消息:{}'.format(msg))
                    if msg == 'n' and (time.time() - current_time) >= 30.0:
                        conn.send('正在断开连接\n'.encode('utf-8'))
                        conn.send('连接已断开\n'.encode('utf-8'))
                        break
                    elif msg == 'python':
                        src_file = open('./CODERESOURCE.py', 'w', encoding='utf-8')
                        result_file = open('RETURNRESULT.txt', 'w+', encoding='utf-8')
                        t3 = threading.Thread(target=pyhon365)
                        t3.setDaemon(True)
                        t3.start()
                        t3.join()
                        src_file.close()
                        result_file.close()
                        current_time = time.time()
                        continue
                    conn.send('消息已收到\n'.encode('utf-8'))
                    current_time = time.time()
                else:
                    break
            except BaseException:
                break
        conn.close()
        print("end of servive")

java客户端

import java.util.*;
import org.apache.http.util.*;
import java.net.*;
import java.io.*;
import org.json.JSONObject;
import java.util.regex.*;

public class Main {
    public static boolean onOff = true;
    public static void main (String args[]) {
        try{
            Socket s = new Socket("192.168.0.104",9999);
            BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
            OutputStream O = s.getOutputStream();
            DataOutputStream os = new DataOutputStream(O);
            Rd is = new Rd();
            
            is.main(s);
            Thread t = new Thread(is);
            t.start();
            String readline;
            while (true) {
                readline = rd.readLine();
                if (readline.equals("exit")) {break;}
                os.writeUTF(readline);
                os.flush();
                if (readline.equals("python")) {
                    onOff = false;
                    System.out.println("PYTHON 3.6.5");
                    System.out.print(">>>");
                    while (true) {
                        readline = rd.readLine();
                        os.writeUTF(readline);
                        os.flush();
                        if (readline.equals("exit")){break;}
                    }
                }
            }
            os.close();
            s.close();
        }catch (Exception e) {
            System.out.println("连接异常");
        }
    }
}

class Rd implements Runnable {
    Socket sk = null;
    public void main (Socket s) {
        sk = s;
        System.out.println(""+sk);
    }
    @Override
    public void run() {
        Pattern p = Pattern.compile("... +");
        try{
            InputStream is=sk.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String info;
                
                while((info=in.readLine())!=null){
                    if (Main.onOff) {
                        System.out.println("Python服务器:"+info);
                    }else{
                        Matcher m = p.matcher(info);
                        if (info.equals("python已退出")) {Main.onOff = true;}
                        if (info.equals(">>>") | m.matches()) {
                            System.out.print(info);
                        }else{
                            System.out.println(info);
                        }
                    }
                }
            
        } catch (IOException e){
            System.out.println("连接异常");
            //e.printStackTrace();
        }
    }
}

 

posted @ 2019-06-20 23:00  码迷-wjz  阅读(543)  评论(0)    收藏  举报