java
网络编程
serversocket 解析inputstream时,出现线程卡死的情况:不能接收到客户端发送的数据,也不返回数据。
解决方法1:
//读取输入流
public static byte[] readIn(InputStream in) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
int count = 0;
while (count == 0) {
count = in.available();
}
byte[] buffer = new byte[count];
int len = 0;
while ((len = in.read(buffer)) != -1) {
//等待read(buffer)返回-1时,线程卡死 ,
//需要在客户端socket.shutdownOutPut 关闭输出流;
outputStream.write(buffer, 0, len);
}
return outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return outputStream.toByteArray();
}
client
public static void main(String[] args) {
Socket socket = null;
OutputStream out = null;
InputStream in = null;
String ip;
int port = 30000;
try {
ip = InetAddress.getLocalHost().getHostAddress();//
socket = new Socket(ip, port);
String outStr = "你好,我是客户端!";
out = socket.getOutputStream();
out.write(outStr.getBytes());
out.flush();
socket.shutdownOutput();//关闭输出流
in = socket.getInputStream();
byte[] getData = SimpleSocketServer.readIn(in);
socket.shutdownInput();
System.out.println("收到服务器消息:" + new String(getData));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
解决方法2:
使用java.io包下:
DataInputStream,DataOutputStream工具类
server socket
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
OutputStream out = null;
InputStream in = null;
int port = 30000;
try {
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());//receive
System.out.println("客户端发送内容为:" + dataInputStream.readUTF());
String outStr = "你好,服务端已经收到信息";
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());//send
dataOutputStream.writeUTF("客服端:"+outStr);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
client
public static void main(String[] args) {
Socket socket = null;
OutputStream out = null;
InputStream in = null;
String ip;
int port = 30000;
try {
ip = InetAddress.getLocalHost().getHostAddress();//
socket = new Socket(ip, port);
String outStr = "你好,我是客户端!";
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());//send
dataOutputStream.writeUTF(outStr);
DataInputStream inStr = new DataInputStream(socket.getInputStream());
System.out.println("收到服务器消息=" + inStr.readUTF());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
备注:
在服务inputStream时,也可以不等待返回-1,直接in.read(count),一次性全量读取字节;
在数据量小的情况下可以使用,如果数据量过大,这种方法是有潜在问题的。