首页 > 其他 > 详细

Socket通信

时间:2017-09-04 15:41:49      阅读:234      评论:0      收藏:0      [点我收藏+]

项目需求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;
}

Socket通信

原文:http://www.cnblogs.com/leirenyuan/p/7473827.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!