短连接:只进行一次收发就是短连接
长连接:发送消息后不关闭就是长连接,但会存在粘包等问题。
接收:可以写入一个循环一直接收
try{
ServerSocket serverSocket = new ServerSocket("8080");
while(true){
Socket accept = serverSocket.accept();
InputStream inputStream = null;
OutputStream outputStream=null;
try {
inputStream = accept.getInputStream();
outputStream=accept.getOutputStream();
// 前8个字节,表示本次发送消息的长度
byte[] b = new byte[8];
inputStream.read(b);
int len = Integer.parseInt(new String(b, "UTF-8"));
// 根据得到的消息长度len ,设置byte数组进行接收消息
b = new byte[len];
inputStream.read(b);
String s = new String(b);
System.out.println("收到数据: "+s);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (inputStream != null){
inputStream.close();
}
if (outputStream!=null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}catch(Exception e){
e.printStackTrace();
}
// 没有关闭accept,就会一直循环接收消息。
发送端:
//发送消息
Socket socket = new Socket("127.0.0.1",8080);
OutputStream outputStream = socket.getOutputStream();
String s = "你好,世界";
byte[] bytes = s.getBytes("UTF-8");
//先发送一个八位的,表示此次消息的长度。该方法贴在后边
outputStream.write(int2Bytes8(bytes.length));
outputStream.write(bytes);
//接收反馈
InputStream inputStream = socket.getInputStream();
byte[] bytes1 =new byte[1024];
inputStream.read(bytes1);
System.out.println("服务器反馈:"+new String(bytes1));
inputStream.close();
outputStream.close();
将消息长度自动补至八位:
public static byte[] int2Bytes8(int num) {
StringBuffer sb = new StringBuffer(String.valueOf(num));
int length = 8 - sb.length();
for (int i = 0; i < length; i++) {
sb.insert(0, '0');
}
return sb.toString().getBytes();
}
欢迎各位大佬指点。