Socket communication instance code between Python and Java

  • 2020-05-26 09:31:28
  • OfStack

Socket communication between Python and Java

Done before 1 Java communication tool, has the basic function such as message sent files. Can you also know Java written either AWT or Swing interface, it is not to see, for those of us developers also good, if it is Release went out to the user, and then must be despised it. Use C + +, code is also very much (QT do very well!) , but I'll switch to Python so that I can use wxPython as the interface.

Only the core implementation and ideas are given here

Server(Java) receives files sent from Clinet(Python)

JServer. java


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
 
public class JServer implements Runnable {
 
  ServerSocket ss;
 
  public JServer() throws Exception {
    ss = new ServerSocket(8086);
    new Thread(this).start();
  }
 
  @Override
  public void run() {
    int i = 0;
    System.out.println("server startup.");
    while (true) {
      try {
        Socket s = ss.accept();
        //  Each client 1 Three processing threads 
        new Handler(s, i).start();
        i++;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
 
  }
 
  public static void main(String[] args) {
    try {
      new JServer();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 
}
 
class Handler extends Thread {
  Socket s;
  int id;
 
  public Handler(Socket s, int id) {
    this.s = s;
    this.id = id;
  }
 
  @Override
  public void run() {
    System.out.println("in handling..");
 
    FileOutputStream fos = null;
    try {
      InputStream is = s.getInputStream();
      BufferedReader in = new BufferedReader(new InputStreamReader(is));
      //  Reads the file name sent from the client 
      String filename = in.readLine();
      System.out.println("read line " + id + " :" + filename);
      File file = new File(filename);
 
      int len = 0;
      int BUFSIZE = 4*1024;
      byte[] by = new byte[BUFSIZE * 1024];
      fos = new FileOutputStream(file);
      while ((len = is.read(by, 0, BUFSIZE)) != -1) {
        fos.write(by, 0, len);
        fos.flush();
      }
      System.out.println("done.");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      //  You don't want my hand is out of control on the server   Turn off the socket Otherwise, Python  There will be errors Errno 10054 Just tell the client to shut down 
      try {
        fos.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

Python client


# -*- coding: utf-8 -*-
#!/usr/bin/python
#coding=utf-8
import time
import threading
import socket
import os
 
class Client():
  def __init__(self):
    address = ('127.0.0.1', 8086)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(address)
    fn = 'test.zip'
    ff = os.path.normcase(fn)
 
    try:
      f = open(fn, 'rb')
      sendFile = SendFile(s,f)
      sendFile.start()
      print 'start to send file.'
    except IOError:
      print 'open err'
 
 
class SendFile(threading.Thread):
  def __init__(self, sock, file):
    threading.Thread.__init__(self)
    self.file = file
    self.sock = sock
 
  def run(self):
    print self.file
    BUFSIZE = 1024
    count = 0
    name = self.file.name+'\r'
         #  before 1k The byte is used to send the file name to the server  1 Need to add '\r', Otherwise the server won't readline the 
    for i in range(1, BUFSIZE - len(self.filename) -1):
      name += '?'
    print name
    self.sock.send(name)
    while True:
      print BUFSIZE
      fdata = self.file.read(BUFSIZE)
      if not fdata:
        print 'no data.'
        break
      self.sock.send(fdata)
      count += 1
      if len(fdata) != BUFSIZE:
        print 'count:'+str(count)
        print len(fdata)
      nRead = len(fdata)
 
    print 'send file finished.'
    self.file.close()
    self.sock.close()
    print 'close socket'
 
c = Client()

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: