Socket通信

项目需求java客户端与C++服务端进行通信,本人对这方面是小白一枚,经过多天查资料,整理了一点,特贴出来,万一哪天用到了,回来瞅一眼,代码如下:

public static final String IP_ADDR = "127.0.0.1";//服务器地址
public static final int PORT = 4999;//服务器端口号
private static DataOutputStream outStr = null;
private static InputStream inStr = null;

public AjaxJson socketMsg() throws IOException {
AjaxJson ajaxJson = new AjaxJson();
// String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
String str = "abc";
Socket socket = null;
try {
//创建一个流套接字并将其连接到指定主机上的指定端口号
socket = new Socket(IP_ADDR, PORT);
//读取服务器端数据
// DataInputStream input = new DataInputStream(socket.getInputStream());
inStr = socket.getInputStream();
//向服务器端发送数据
outStr = new DataOutputStream(socket.getOutputStream());
outStr.writeUTF(str);
// String ret = input.readUTF();
byte[] b = new byte[1024];
int r = inStr.read(b);
String ret = "";
if (r > -1) {
ret = new String(b);
System.out.println("服务器端返回过来的是: " + ret);
System.out.println("客户端将关闭连接");
ajaxJson.setMsg("请求成功");
ajaxJson.setSuccess(true);

}

} catch (Exception e) {
System.out.println("客户端异常:" + e.getMessage());
ajaxJson.setMsg("服务器异常");
ajaxJson.setSuccess(false);
}finally {
outStr.close();
inStr.close();
socket.close();
}
return ajaxJson;
}
原文地址:https://www.cnblogs.com/leirenyuan/p/7473827.html