python、java、socket通信



一、Python 或Java 与 Python 间通信

1、json当作字典来处理,并传递字典

(1)、Client 端

import socket
import json
HOST='localhost'
PORT=10001
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)      #定义socket类型,网络通信,TCP
s.connect((HOST,PORT))       #要连接的IP与端口
sendData ={
     '2016-07-21':{
         'value':3934,
         'titles':[u'标题1',u'标题2',u'标题3']
     },
     '2016-07-22':{
         'value':1109,
         'titles':[u'标题4',u'标题5',u'标题6']
     },
    '2016-07-23':{
         'value':2365,
         'titles':[u'标题7',u'标题8',u'标题9']
     }
}
s.sendall(repr(sendData)); <strong>#用repr()函数将字典序列化再传递,不然不能进行传递</strong>
s.close()   #关闭连接

(2)、Server 端

import socket   #socket模块
import commands   #执行系统命令模块
HOST='localhost'
PORT=10001
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)   #定义socket类型,网络通信,TCP
s.bind((HOST,PORT))   #套接字绑定的IP与端口
s.listen(1)         #开始TCP监听
while True:
    conn,addr=s.accept()   #接受TCP连接,并返回新的套接字与IP地址
    print'Connected by',addr    #输出客户端的IP地址
    data=conn.recv(10024)    #把接收的数据实例化
    if len(data.strip()) ==0:
        conn.sendall('Done.')
    else:
        recData = eval(data)    <strong>#用eval()函数恢复序列化后的json(字典)对象,才能进行进一步操作</strong>
        for key,value in recData.items():
            print key, value['value']
            for item in value['titles']:
                print item,
            print
        conn.sendall('Successful')   #否则就把结果发给对端(即客户端)
conn.close()

2、直接传递json数据

1、Client 端

(1)、client端用python代码编写请求代码

import socket
import json
HOST='localhost'
PORT=10001
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)      #定义socket类型,网络通信,TCP
s.connect((HOST,PORT))       #要连接的IP与端口
sendData ={
     '2016-07-21':{
         'value':3934,
         'titles':[u'标题1',u'标题2',u'标题3']
     },
     '2016-07-22':{
         'value':1109,
         'titles':[u'标题4',u'标题5',u'标题6']
     },
    '2016-07-23':{
         'value':2365,
         'titles':[u'标题7',u'标题8',u'标题9']
     }
}
message = json.dumps(sendData)  #json 经过转换后才能传输
s.sendall(message)      #把命令发送给对端

response=s.recv(10240)     #把接收的数据定义为变量
jresp = json.loads(response)
print "Recv",jresp         #输出返回的json

(2)、client端用JAVA编写请求代码

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import org.json.JSONObject;
public class Client {
	public static void main(String args[]) throws Exception {
		   //为了简单起见,所有的异常都直接往外抛
		String host = "localhost";  //要连接的服务端IP地址
		int port = 10001;   //要连接的服务端对应的监听端口
		   //与服务端建立连接
		Socket client = new Socket(host, port);
		   //建立连接后就可以往服务端写数据了

		HashMap<String,HashMap> sendData = new HashMap<String,HashMap>();
		
		String[] date = {"2016-07-24","2016-07-25","2016-07-26","2016-07-27","2016-07-28"};
		for (int i = 0; i < date.length; i++ ){
			HashMap<String,Object> item = new HashMap<String,Object>();
			item.put("vallue", 1234);
			String [] titles = {"标题1","标题2","标题3"};
			item.put("titles",titles);
			sendData.put(date[i],item);
		}

		DataOutputStream outputStream = null;
		outputStream = new DataOutputStream(client.getOutputStream());
		
		JSONObject json = new JSONObject(sendData);
		String jsonString = json.toString();
		byte[] jsonByte = jsonString.getBytes();
		
        System.out.println("发的数据长度为:"+jsonByte.length);  
        outputStream.write(jsonByte);  
        outputStream.flush();  
        System.out.println("传输数据完毕");  
        client.shutdownOutput(); 
		
        
        //以下为接受服务器端发来的数据
        DataInputStream inputStream = null;  
        String strInputStream ="";  
        
        inputStream = new DataInputStream(new BufferedInputStream(client.getInputStream()));   
        byte[] by = new byte[20480];  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int nbyte;
        while((nbyte=inputStream.read(by))!=-1){  
            baos.write(by,0,nbyte);           
        }  
        strInputStream = new String(baos.toByteArray()); 

        JSONObject js = new JSONObject(strInputStream);
        
        System.out.println(js.toString());
//        System.out.println(js.get("nextDayHot")); 
		
	}
}

2、Server端

#__author__ = 'Administrator'
# -*- coding: utf-8 -*-
# -*- coding:utf-8 -*-
#

import socket
import threading
import SocketServer
import json, types,string
import os, time

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = self.request.recv(102400)
        jdata = json.loads(data,encoding="GBK")     #编码转换

        for date in jdata.keys():
            print date.encode('utf-8'), jdata[date]["titles"][0],jdata[date]["titles"][1],jdata[date]["titles"][2]
        # 下面是返回给client的json格式数据
        topWords = {}
        topWords['南海'] = 0.123
        topWords['南沙'] = 0.543

        response = {}

        response['nextDayHot'] = 123
        response['topWords'] = topWords

        jresp = json.dumps(response)
        self.request.sendall(jresp)

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = "localhost", 10001

    SocketServer.TCPServer.allow_reuse_address = True
    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    ip, port = server.server_address

    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(target = server.serve_forever)

    # Exit the server thread when the main thread terminates
    server_thread.daemon = True
    server_thread.start()
    print "Server loop running in thread:", server_thread.name
    print " .... waiting for connection"

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

即可以通过python 或者java 编写的客户端,以json 数据格式的形式与python端编写的服务端进行数据通信。

二、JAVA与JAVA间通信

1、client端

package server.client;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class Client {
	
	public static List readFiles(String path) throws IOException{
		FileInputStream fis = new FileInputStream(path); 
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 
        BufferedReader br = new BufferedReader(isr); 
		
        List document = new ArrayList();
        List article = new ArrayList();
        
        String line = null;
        int index = 0;
		while((line = br.readLine()) != null) {
			article.add(line.trim());
			index += 1;
			if (index % 2 == 0){
				document.add(new ArrayList(article));
				article.clear();
			}
		}
		return document;
	}
	
	public static void main(String args[]) throws Exception {
		   //为了简单起见,所有的异常都直接往外抛
		String host = "101.200.146.57";  //要连接的服务端IP地址
		int port = 10086;   //要连接的服务端对应的监听端口
		   //与服务端建立连接
		Socket client = new Socket(host, port);
		   //建立连接后就可以往服务端写数据了
		ObjectOutputStream writer = new ObjectOutputStream(client.getOutputStream());
	    
		
		System.out.println(new Date());
		List relDoc = readFiles("file//relatedDoc.txt");
		List unrelDoc = readFiles("file//unrelatedDoc.txt");
		List needDealDoc = readFiles("file//dealDoc.txt");
		
		HashMap<String,List> map= new HashMap<String,List>();
//		System.out.println("this is Clent");
		
		map.put("relDoc", relDoc);
	        map.put("unrelDoc", unrelDoc);
	        map.put("needDealDoc", needDealDoc);
	    
		writer.writeObject(map);
		writer.flush();
		
		ObjectInputStream br = new ObjectInputStream(new BufferedInputStream(client.getInputStream()));
		List similarityList = (List) br.readObject();
		
		System.out.println(similarityList);
		System.out.println(new Date());
		writer.close();
		br.close();
		
	}
	
}

2、Server端

package server.client;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import text.sort.*;
public class Server {
	
	public static void main(String args[]) throws IOException {
	      //为了简单起见,所有的异常信息都往外抛
		int port = 10086;
	      //定义一个ServerSocket监听在端口8899上
	    ServerSocket server = new ServerSocket(port);
//	    server.setReceiveBufferSize(20480000);
	    
	    while (true) {
	         //server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
	    	Socket socket = server.accept();
	         //每接收到一个Socket就建立一个新的线程来处理它
	        new Thread(new Task(socket)).start();
	    }
	}   
	   /**
	    * 用来处理Socket请求的
	   */
	public static class Task implements Runnable {
	 
		public Socket socket;
	      
	    public Task(Socket socket) {
	    	this.socket = socket;
	    }
	      
	    public void run() {
	    	try {
	    		handleSocket();
	        }
	    	catch (Exception e) {
	            e.printStackTrace();
	        }
	    } 
	      /**
	       * 跟客户端Socket进行通信 * @throws Exception
	       */
	    public void handleSocket() throws Exception {
	    	 ObjectInputStream br = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
	    	 ObjectOutputStream writer = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));
	    	 
	         HashMap map = (HashMap) br.readObject();
	         List list = (List)map.get("test");
	         List relDoc = (List)map.get("relDoc");
	         List unrelDoc = (List)map.get("unrelDoc");
	         List needDealDoc = (List)map.get("needDealDoc");
	         //读完后写一句
         
	         List similarityList = VecSpaModel.VSMStart( relDoc, unrelDoc, needDealDoc);

	         
//	         System.out.println(similarityList.size());
	         writer.writeObject(similarityList);
	         writer.flush();
	         writer.close();
	         br.close();
	         socket.close();
	   }
   }
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值