Python与Java间Socket通信实例代码


Posted in Python onMarch 06, 2017

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-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'



 # 前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()

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Python 相关文章推荐
Python中的ctime()方法使用教程
May 22 Python
Python iter()函数用法实例分析
Mar 17 Python
python逐行读写txt文件的实例讲解
Apr 03 Python
Python 实现选择排序的算法步骤
Apr 22 Python
用Python写一段用户登录的程序代码
Apr 22 Python
windows下python安装pip图文教程
May 25 Python
解决django服务器重启端口被占用的问题
Jul 26 Python
django+tornado实现实时查看远程日志的方法
Aug 12 Python
基于python实现破解滑动验证码过程解析
May 28 Python
Python爬虫之Selenium实现窗口截图
Dec 04 Python
Python趣味挑战之给幼儿园弟弟生成1000道算术题
May 28 Python
python基础入门之字典和集合
Jun 13 Python
python使用arcpy.mapping模块批量出图
Mar 06 #Python
python与php实现分割文件代码
Mar 06 #Python
windows系统下Python环境的搭建(Aptana Studio)
Mar 06 #Python
windows下安装Python和pip终极图文教程
Mar 05 #Python
python爬虫的工作原理
Mar 05 #Python
python操作mysql数据库
Mar 05 #Python
Windows安装Python、pip、easy_install的方法
Mar 05 #Python
You might like
PHP 前加at符合@的作用解析
2015/07/31 PHP
php bootstrap实现简单登录
2016/03/08 PHP
php实现与python进行socket通信的方法示例
2017/08/30 PHP
javascript复制对象使用说明
2011/06/28 Javascript
jQuery EasyUI API 中文文档 - NumberBox数字框
2011/10/13 Javascript
IE事件对象(The Internet Explorer Event Object)
2012/06/27 Javascript
谈谈关于JavaScript 中的 MVC 模式
2013/04/11 Javascript
node.js中watch机制详解
2014/11/17 Javascript
JavaScript中的console.trace()函数介绍
2014/12/29 Javascript
JavaScript实现按照指定长度为数字前面补零输出的方法
2015/03/19 Javascript
JavaScript使用pop方法移除数组最后一个元素用法实例
2015/04/06 Javascript
JavaScript对Cookie进行读写操作实例
2015/07/25 Javascript
js中编码函数:escape,encodeURI与encodeURIComponent详解
2017/03/21 Javascript
nodejs密码加密中生成随机数的实例代码
2017/07/17 NodeJs
基于javascript的无缝滚动动画1
2020/08/07 Javascript
[56:00]DOTA2上海特级锦标赛主赛事日 - 4 胜者组决赛Secret VS Liquid第一局
2016/03/05 DOTA
编写Python爬虫抓取豆瓣电影TOP100及用户头像的方法
2016/01/20 Python
简单讲解Python编程中namedtuple类的用法
2016/06/21 Python
全面了解Python环境配置及项目建立
2016/06/30 Python
python 网络编程常用代码段
2016/08/28 Python
Python实现简易Web爬虫详解
2018/01/03 Python
Python3 修改默认环境的方法
2019/02/16 Python
numpy ndarray 按条件筛选数组,关联筛选的例子
2019/11/26 Python
python实现百度OCR图片识别过程解析
2020/01/17 Python
keras之权重初始化方式
2020/05/21 Python
python 视频下载神器(you-get)的具体使用
2021/01/06 Python
Haglöfs瑞典官方网站:haglofs火柴棍,欧洲顶级户外品牌
2018/10/18 全球购物
利用promise及参数解构封装ajax请求的方法
2021/03/24 Javascript
大学生个人求职信范文
2013/09/21 职场文书
交通事故调解协议书
2014/04/16 职场文书
2014年有孩子的离婚协议书范本
2014/10/08 职场文书
组织委员竞选稿
2015/11/21 职场文书
python基于tkinter制作m3u8视频下载工具
2021/04/24 Python
springboot实现string转json json里面带数组
2022/06/16 Java/Android
win10重装系统后上不了网怎么办 win10重装系统网络故障的解决办法
2022/07/23 数码科技
MySQL自定义函数及触发器
2022/08/05 MySQL