Python與Java間Socket通訊執行個體代碼,pythonsocket

來源:互聯網
上載者:User

Python與Java間Socket通訊執行個體代碼,pythonsocket

Python與Java間Socket通訊

  之前做過一款Java的通訊工具,有發訊息發檔案等準系統.可大家也都知道Java寫的介面無論是AWT或Swing,那簡直不是人看的,對於我們這些開發人員還好,如果是Release出去給使用者看,那必須被鄙視到底.用C++的話,寫的代碼也是非常多的(QT這方面做得很好!),但我這裡改用Python,以便到時用wxPython做介面.而且這兩者跨平台也做得非常好.

  這裡只給出核心實現以及思路

  Server(Java)接收從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();        // 每個用戶端一個處理線程        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));      // 從用戶端讀取發送過來的檔案名稱      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 {      // 服務端就不要手賤 關了socket否則Python 會出現錯誤Errno 10054讓用戶端關掉就行啦      try {        fos.close();      } catch (IOException e) {        e.printStackTrace();      }    }  }}

   Python用戶端

# -*- coding: utf-8 -*-#!/usr/bin/python#coding=utf-8import timeimport threadingimport socketimport 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'         # 前1k位元組是為了給服務端傳送檔案名 一定要加上'\r',不然服務端就不能readline了    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()

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.