http协议快还是socket快,还是传对象快

http传对象就是传json字符串。

socket传对象也可以传字符串,这个不谈。我们以传字节数组与传对象来对比。传字节数组又可以分为单个字节单个字节的传和有一个Buffer数组的传。


客户端代码:

package net.highersoft.ssm;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

import cn.hutool.http.HttpUtil;
import net.highersoft.ssm.controller.SerializeUtil;
import net.highersoft.ssm.entity.Result;



public class Client {
	private static Logger log=LoggerFactory.getLogger(Client.class);
	static String ip="192.168.0.103";
	//static String ip="localhost";
	public static void main(String[] args) throws Exception{
		
		getHttp();
		getSingleSocket();
		getSocket();
		getSocketObj();
		
		
		
		for(int i=0;i<20;i++) {
			getSocketObj();
		}
		for(int i=0;i<20;i++) {
			getHttp();
		}
		
		
		

	}
	private static void getHttp() {
		String url="http://"+ip+":8091/getJson";
		Calendar start=Calendar.getInstance();
		String rst=HttpUtil.get(url);
		log.info("get http response time:{}ms length:{}",(Calendar.getInstance().getTimeInMillis()-start.getTimeInMillis()),rst.length());
	}
	private static void getSingleSocket() throws Exception{
		Socket s=new Socket(ip,8022);
		List<Byte> rsp=new ArrayList<>();
		Calendar start=Calendar.getInstance();
		InputStream is=s.getInputStream();
		int b=-1;
		
		while((b=is.read())!=-1) {
			rsp.add((byte)b);
			
		}
		is.close();
		Calendar end=Calendar.getInstance();
		
		
		
		
		List<Result> rst=(List<Result>)SerializeUtil.unserialize(rsp.toArray(new Byte[rsp.size()]));
		log.info("get getSingleSocket response time:{}ms length:{}",(end.getTimeInMillis()-start.getTimeInMillis()),new Gson().toJson(rst).length());
	}
	private static void getSocket() throws Exception{
		Socket s=new Socket(ip,8022);
		List<byte[]> rsp=new ArrayList<>();
		Calendar start=Calendar.getInstance();
		InputStream is=s.getInputStream();
		int b=-1;
		int sum=0;
		List<Integer> batchNum=new ArrayList<>();
		byte tmp[]=new byte[1000];
		int rstNum=-1;
		while((rstNum=is.read(tmp))!=-1) {
			rsp.add(tmp.clone());
			sum+=rstNum;
			batchNum.add(rstNum);
			
		}
		is.close();
		
		
		byte[] rspByte=new byte[sum];
		int startIndex=0;
		for(int i=0;i<rsp.size();i++) {
			byte[] bs=rsp.get(i);
			int thisBatchNum=batchNum.get(i);
			System.arraycopy(bs, 0, rspByte, startIndex, thisBatchNum);
			startIndex+=thisBatchNum;
		}
		Calendar end=Calendar.getInstance();
		
		List<Result> rst=(List<Result>)SerializeUtil.unserialize(rspByte);
		log.info("get Batch Socket response time:{}ms length:{}",(end.getTimeInMillis()-start.getTimeInMillis()),new Gson().toJson(rst).length());
	}
	
	private static void getSocketObj() throws Exception{
		Socket s=new Socket(ip,8021);
		
		Calendar start=Calendar.getInstance();

		InputStream is=s.getInputStream();
		ObjectInputStream isObj=new ObjectInputStream(is);
		List<Result> rst=(List<Result>)isObj.readObject();
		Calendar end=Calendar.getInstance();
		
		log.info("get SocketObj response time:{}ms length:{}",(end.getTimeInMillis()-start.getTimeInMillis()),new Gson().toJson(rst).length());
	}
	

}


http服务端:

package net.highersoft.ssm.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import net.highersoft.ssm.entity.Result;

@RestController
public class TestController {
	private static Logger log=LoggerFactory.getLogger(TestController.class);
	private Gson gson=new Gson();
	@RequestMapping("/")
	public Map<String,String> home() {
		Map<String,String> map=new HashMap<>();
		map.put("key", "value");
		
		return map;
	}
	
	@RequestMapping("/getJson")
	@ResponseBody
	public List<Result> getJson() {
		List<Result> rst=getRst();
		Calendar jsonStart=Calendar.getInstance();
		String jsonObj=gson.toJson(rst);
		Calendar start=Calendar.getInstance();
		List<Result> rst2=gson.fromJson(jsonObj, new TypeToken<List<Result>>() {}.getType());
		log.info("in getJson length:{} parseJson:{}ms object2json:{}ms",rst2.size(),Calendar.getInstance().getTimeInMillis()-start.getTimeInMillis() ,start.getTimeInMillis()-jsonStart.getTimeInMillis());
		return rst2;
	}
	public static List<Result> getRst(){
		int keyLen=3000;
		List<Result> rst=new ArrayList();
		for(int i=0;i<keyLen;i++) {
    		Result rs=new Result();
    		rs.setAipicscore((float)(i*1.0));
    		rs.setCatalogs(new String[] {String.valueOf(i)});
    		rs.setColdStatus(String.valueOf(i));
    		rs.setFilterLowConvert(String.valueOf(i));
    		rs.setGradingVal(String.valueOf(i));
    		rs.setGreenScreenFlag(String.valueOf(i));
    		rs.setIsGreen((byte)(i%2));
    		rs.setRectype(String.valueOf(i));
    		rs.setScore((float)(i*1.0));
    		rs.setSimitemcode(String.valueOf(i));
    		rs.setSimscore((float)(i*1.0));
    		rs.setSrcitemcode(String.valueOf(i));
    		
    		rst.add(rs);
    	}
		return rst;
	}
	public static void main(String arsg[]) {
		char a='汉';
		System.out.println(a);
	}

}


Socket 字节服务端代码:

package net.highersoft.ssm.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HSocketServer {
	private static Logger log=LoggerFactory.getLogger(HSocketServer.class);
	private static HSocketServer  server=null;

	
	public static void init(){
		new Thread() {
			public void run() {
				int port=8022;
				log.info("Server starting "+port+"...");
				server=new HSocketServer();
					// 使用8000端口提供服务
					ServerSocket server;
					try {
						server = new ServerSocket(port);			
						while (true) {
							// 阻塞,直到有客户连接
							Socket sk=null;
							try {						
								sk = server.accept();						
								//sk.setKeepAlive(true);						
								sk.setSoTimeout(10000);
								//无穷大
								//sk.setSoTimeout(0);
								log.info("Accepting Connection... "+port);
								new ReceivThread(sk).start();						
							} catch (IOException e) {
								e.printStackTrace();
								
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
			}
		}.start();
		
		
	}
	public static void main(String[] args) throws IOException {
		HSocketServer server=new HSocketServer();
		server.init();
	}
}
class ReceivThread extends Thread{
	private static final Logger log=LoggerFactory.getLogger(ReceivThread.class);
	private Socket socket;

	public ReceivThread(Socket socket) {
		super();
		this.socket = socket;
	}
	public void run(){
		try{
			
			OutputStream os=socket.getOutputStream();
			os.write(SerializeUtil.serialize(TestController.getRst()));
			os.close();
			
			log.info("thread exist");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}



Socket 对象服务端代码:

package net.highersoft.ssm.controller;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HObjSocketServer {
	private static Logger log=LoggerFactory.getLogger(HObjSocketServer.class);
	private static HObjSocketServer  server=null;

	
	public static void init() {
		new Thread() {
			public void run() {
				int port = 8021;
				log.info("Server starting " + port + "...");
				server = new HObjSocketServer();
				// 使用8000端口提供服务
				ServerSocket server;
				try {

					server = new ServerSocket(port);
					while (true) {
						// 阻塞,直到有客户连接
						Socket sk = null;
						try {
							sk = server.accept();
							// sk.setKeepAlive(true);
							sk.setSoTimeout(10000);
							// 无穷大
							// sk.setSoTimeout(0);
							log.info("Accepting Connection... " + port);
							new ReceivObjThread(sk).start();
						} catch (IOException e) {
							e.printStackTrace();

						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();

	}
	public static void main(String[] args) throws IOException {
		HObjSocketServer server=new HObjSocketServer();
		server.init();
	}
}
class ReceivObjThread extends Thread{
	private static final Logger log=LoggerFactory.getLogger(ReceivThread.class);
	private Socket socket;

	public ReceivObjThread(Socket socket) {
		super();
		this.socket = socket;
	}
	public void run(){
		try{
			
			OutputStream os=socket.getOutputStream();
			ObjectOutputStream oos= new ObjectOutputStream(os);
			oos.writeObject(TestController.getRst());
			os.close();
			
			log.info("thread exist");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}



工具类:

package net.highersoft.ssm.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
	public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
         ByteArrayOutputStream baos = null;
         try {
              // 序列化
             baos = new ByteArrayOutputStream();
             oos = new ObjectOutputStream(baos);
             oos.writeObject(object);
              byte[] bytes = baos.toByteArray();
              return bytes;
        } catch (Exception e) {

        }
         return null;
  }
	
   public static Object unserialize( byte[] bytes) {
        ByteArrayInputStream bais = null;
         try {
              // 反序列化
             bais = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bais);
              return ois.readObject();
        } catch (Exception e) {

        }
         return null;
  }
   public static Object unserialize( Byte[] bytes) {
	   byte[] bs=new byte[bytes.length];
	   for(int i=0;i<bytes.length;i++) {
		   bs[i]=bytes[i];
	   }
       ByteArrayInputStream bais = null;
        try {
             // 反序列化
            bais = new ByteArrayInputStream(bs);
            ObjectInputStream ois = new ObjectInputStream(bais);
             return ois.readObject();
       } catch (Exception e) {

       }
        return null;
 }
}


启动函数:

@Configuration 
@ComponentScan 
@EnableAutoConfiguration 
public class Application { 
    public static void main(String[] args) { 
        SpringApplication.run(Application.class); 
        HSocketServer server=new HSocketServer();
		server.init();
		
		HObjSocketServer serverObj=new HObjSocketServer();
		serverObj.init();
    } 
}


maven pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>net.highersoft</groupId>
	<artifactId>ssm</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<!-- <version>1.5.2.RELEASE</version> -->
		<version>2.1.0.RELEASE</version> 
		
		<relativePath />
	</parent>
	<dependencies>
		<!-- spring boot实现Java Web服务 -->
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<!-- 
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.12</version>
		</dependency>
		 -->
		 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
		
	 <dependency>
			<!-- jsoup HTML parser library @ http://jsoup.org/ -->
			<groupId>org.jsoup</groupId>
			<artifactId>jsoup</artifactId>
			<version>1.9.2</version>
		</dependency>
         <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.7</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.0</version>
        </dependency>
        <dependency>
		    <groupId>com.google.guava</groupId>
		    <artifactId>guava-base</artifactId>
		    <version>r03</version>
		</dependency>
       
	</dependencies>
	
	<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.0.2</version>
                    <configuration>
                        <archive>
                            <manifest>
                                <mainClass>net.highersoft.ssm.Application</mainClass>
                            </manifest>
                        </archive>
                    </configuration>
                </plugin>
        </plugins>
    </build>
</project>


实验结果:

14:40:45.808 [main] INFO net.highersoft.ssm.Client - get http response time:329ms length:698791
14:40:46.403 [main] INFO net.highersoft.ssm.Client - get getSingleSocket response time:444ms length:698791
14:40:46.560 [main] INFO net.highersoft.ssm.Client - get Batch Socket response time:115ms length:698791
14:40:46.804 [main] INFO net.highersoft.ssm.Client - get SocketObj response time:219ms length:698791
14:40:46.993 [main] INFO net.highersoft.ssm.Client - get SocketObj response time:174ms length:698791
14:40:47.187 [main] INFO net.highersoft.ssm.Client - get SocketObj response time:173ms length:698791
14:40:47.403 [main] INFO net.highersoft.ssm.Client - get http response time:216ms length:698791
14:40:47.587 [main] INFO net.highersoft.ssm.Client - get http response time:184ms length:698791

结果表明,使用有缓冲区的Socket是最快的。当然,一般http也比较快了。


文/程忠 浏览次数:0次   2021-10-17 14:42:07

相关阅读


评论: