Python與Java間Socket通信實(shí)例代碼
Python與Java間Socket通信
之前做過(guò)一款Java的通訊工具,有發(fā)消息發(fā)文件等基本功能.可大家也都知道Java寫(xiě)的界面無(wú)論是AWT或Swing,那簡(jiǎn)直不是人看的,對(duì)于我們這些開(kāi)發(fā)人員還好,如果是Release出去給用戶(hù)看,那必須被鄙視到底.用C++的話(huà),寫(xiě)的代碼也是非常多的(QT這方面做得很好!),但我這里改用Python,以便到時(shí)用wxPython做界面.而且這兩者跨平臺(tái)也做得非常好.
這里只給出核心實(shí)現(xiàn)以及思路
Server(Java)接收從Clinet(Python)發(fā)送來(lái)的文件
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();
// 每個(gè)客戶(hù)端一個(gè)處理線程
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));
// 從客戶(hù)端讀取發(fā)送過(guò)來(lái)的文件名
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 {
// 服務(wù)端就不要手賤 關(guān)了socket否則Python 會(huì)出現(xiàn)錯(cuò)誤Errno 10054讓客戶(hù)端關(guān)掉就行啦
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Python客戶(hù)端
# -*- 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字節(jié)是為了給服務(wù)端發(fā)送文件名 一定要加上'\r',不然服務(wù)端就不能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()
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
pytest用yaml文件編寫(xiě)測(cè)試用例流程詳解
這篇文章主要介紹了pytest用yaml文件編寫(xiě)測(cè)試用例流程,本文通過(guò)實(shí)例代碼圖文相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12
pandas將Series轉(zhuǎn)成DataFrame的實(shí)現(xiàn)
本文主要介紹了pandas將Series轉(zhuǎn)成DataFrame的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
基于Python實(shí)現(xiàn)wifi連接小程序
這篇文章主要為大家詳細(xì)介紹了如何使用Python編程語(yǔ)言編寫(xiě)一個(gè)簡(jiǎn)單的連接Wi-Fi的程序,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01
Python?seaborn?barplot畫(huà)圖案例
這篇文章主要介紹了Python?seaborn?barplot畫(huà)圖案例,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-07-07
Python 正則表達(dá)式實(shí)現(xiàn)計(jì)算器功能
本篇文章主要介紹了Python 正則表達(dá)式實(shí)現(xiàn)計(jì)算器功能的示例。具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧2017-04-04
Django執(zhí)行源生mysql語(yǔ)句實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Django執(zhí)行源生mysql語(yǔ)句實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11

