import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* Java socket 客户端接受数据
*
* @author graceup<br/>
* @version 1.0<br/>
* @datetime: 2015-6-26 <br/>
*/
public class ReceiveClient {
private final String IP = "127.0.0.1";
private final int PORT = 36000;
// 接收
public String reiceve() throws Exception {
Socket sock = null;
BufferedInputStream in = null;
try {
sock = new Socket(IP, PORT);
in = new BufferedInputStream(sock.getInputStream());
if ((sock == null) || (in == null)) {
throw new Exception("套接口无效,无法读取数据");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bts = new byte[10000];
int totalLen = 0, len = 0;
while ((len = in.read(bts, totalLen, 1000)) != -1) {
totalLen += len;
}
String result = new String(bts); // 注意字符编码
return result.trim();
}
// main函数示例
public static void main(String[] args) {
// 接收报文
try {
String recStr = new ReceiveClient().reiceve();
System.out.println("客户端接收到的结果==" + recStr);
} catch (Exception e) { //
e.printStackTrace();
}
}
}
Java socket 客户端接受数据
最新推荐文章于 2023-06-04 04:54:39 发布