免费咨询医生平台南山网站seo
我在写的时候,我的需求就很简单,写一个服务端,去让别人进行请求,借鉴了很多聊天室什么的,越搞越复杂。
期间也使用到了 BufferedReader中readLine()方法,进行获取客户端传来的数据,本地测试没有问题,一跨服务就不行,困扰我了很久,最终才找到了处理方案,具体看下方代码吧!
服务端:
package com.xinyuan.thirdparty.esb;import com.xinyuan.core.common.util.DateTimeUtil;import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;public class TestMainServer {public static void main(String[] args) throws IOException {ServerSocket server = new ServerSocket(2000);System.out.println("服务端准备就绪!");Socket socket = server.accept();System.out.println("客户端已连接!");InputStream inputStream = socket.getInputStream();byte[] bytes = new byte[2024];inputStream.read(bytes);String message = new String(bytes,"utf-8").trim();System.out.println("接收到客户端发送的数据为:"+message);OutputStream outputStream = socket.getOutputStream();outputStream.write("返回客户端的信息".getBytes(StandardCharsets.UTF_8));}
客户端:
package com.xinyuan.thirdparty.esb;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;//测试客户端
public class TestMainClient {public static void main(String[] args) throws IOException {Socket socket = new Socket("127.0.0.1",2000);BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));PrintStream out = new PrintStream(socket.getOutputStream());String message = "";out.println(message);String response = in.readLine();System.out.println("服务端回应:"+response);socket.close();}
}