我的应用程序中需要进行两个过程(Java和Python)进行通信。我注意到套接字通信占用了93%的运行时间。为什么沟通这么慢?我应该寻找套接字通信的替代方法还是可以使其更快?
更新:我发现了一个简单的修复程序。似乎由于某些未知原因,缓冲输出流并未真正被缓冲。因此,现在我将所有数据放入两个客户端/服务器进程的字符串缓冲区中。我用flush方法将其写入套接字。
我仍然对使用共享内存在进程之间快速交换数据的示例感兴趣。
一些其他信息:
这是服务器端:
public class FastIPC{ public PrintWriter out; BufferedReader in; Socket socket = null; ServerSocket serverSocket = null; public FastIPC(int port) throws Exception{ serverSocket = new ServerSocket(port); socket = serverSocket.accept(); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } public void send(String msg){ out.println(msg); // send price update to socket } public void flush(){ out.flush(); } public String recv() throws Exception{ return in.readLine(); } public static void main(String[] args){ int port = 32000; try{ FastIPC fip = new FastIPC(port); long start = new Date().getTime(); System.out.println("Connected."); for (int i=0; i<50; i++){ for(int j=0; j<100; j++) fip.send("+"); fip.send("."); fip.flush(); String msg = fip.recv(); } long stop = new Date().getTime(); System.out.println((double)(stop - start)/1000.); }catch(Exception e){ System.exit(1); } } }
客户端是:
import sys import socket class IPC(object): def __init__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect(("localhost", 32000)) self.fid = self.s.makefile() # file wrapper to read lines self.listenLoop() # wait listening for updates from server def listenLoop(self): fid = self.fid print "connected" while True: while True: line = fid.readline() if line[0]=='.': break fid.write('.\n') fid.flush() if __name__ == '__main__': st = IPC()
您有很多选择。由于您使用的是Linux,因此可以使用UNIX域套接字。或者,您可以将数据序列化为ASCII或JSon或其他某种格式,然后通过管道,SHM(共享内存段),消息队列,DBUS或类似内容将其送入。值得考虑一下您拥有哪种数据,因为这些IPC机制具有不同的性能特征。USENIX的草稿草案对各种折衷进行了很好的分析,值得一读。
由于您说(在此答案的注释中)说您更喜欢使用SHM,因此这里有一些代码示例可以帮助您入门。使用Python posix_ipc库:
import posix_ipc # POSIX-specific IPC import mmap # From Python stdlib class SharedMemory(object): """Python interface to shared memory. The create argument tells the object to create a new SHM object, rather than attaching to an existing one. """ def __init__(self, name, size=posix_ipc.PAGE_SIZE, create=True): self.name = name self.size = size if create: memory = posix_ipc.SharedMemory(self.name, posix_ipc.O_CREX, size=self.size) else: memory = posix_ipc.SharedMemory(self.name) self.mapfile = mmap.mmap(memory.fd, memory.size) os.close(memory.fd) return def put(self, item): """Put item in shared memory. """ # TODO: Deal with the case where len(item) > size(self.mapfile) # TODO: Guard this method with a named semaphore self.mapfile.seek(0) pickle.dump(item, self.mapfile, protocol=2) return def get(self): """Get a Python object from shared memory. """ # TODO: Deal with the case where len(item) > size(self.mapfile) # TODO: Guard this method with a named semaphore self.mapfile.seek(0) return pickle.load(self.mapfile) def __del__(self): try: self.mapfile.close() memory = posix_ipc.SharedMemory(self.name) memory.unlink() except: pass return
对于Java端,您想创建相同的类,尽管我在评论中说过,JTux似乎提供了等效的功能,并且您需要的API在UPosixIPC类中。
下面的代码概述了您需要实现的东西。但是,缺少一些东西- 异常处理是显而易见的东西,还有一些标志(在UConstant中找到它们),并且您需要添加一个信号量来保护put/ get方法。但是,这应该可以使您走上正确的道路。请记住,一个mmap或内存映射文件是一段RAM的类似文件的接口。因此,您可以像使用fd普通文件一样使用其文件描述符。
put
get
mmap
fd
import jtux.*; class SHM { private String name; private int size; private long semaphore; private long mapfile; // File descriptor for mmap file /* Lookup flags and perms in your system docs */ public SHM(String name, int size, boolean create, int flags, int perms) { this.name = name; this.size = size; int shm; if (create) { flags = flags | UConstant.O_CREAT; shm = UPosixIPC.shm_open(name, flags, UConstant.O_RDWR); } else { shm = UPosixIPC.shm_open(name, flags, UConstant.O_RDWR); } this.mapfile = UPosixIPC.mmap(..., this.size, ..., flags, shm, 0); return; } public void put(String item) { UFile.lseek(this.mapfile(this.mapfile, 0, 0)); UFile.write(item.getBytes(), this.mapfile); return; } public String get() { UFile.lseek(this.mapfile(this.mapfile, 0, 0)); byte[] buffer = new byte[this.size]; UFile.read(this.mapfile, buffer, buffer.length); return new String(buffer); } public void finalize() { UPosix.shm_unlink(this.name); UPosix.munmap(this.mapfile, this.size); } }