网络编程(1)---Socket收发

短连接:只进行一次收发就是短连接
长连接:发送消息后不关闭就是长连接,但会存在粘包等问题。

接收:可以写入一个循环一直接收

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();
	}

欢迎各位大佬指点。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值