应龙
2016-08-04 11:01
package com.lzj.test8_4; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UdpServerThread extends Thread{ private static int count = 0; private DatagramSocket socket; public UdpServerThread(DatagramSocket socket) { this.socket = socket; } @Override public void run() { while(true){ try { //接收来自客户端传来的消息 byte[] bytes = new byte[1024]; DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length); socket.receive(packet); System.out.println(new String(bytes)); //向客户端发送消息 InetAddress addr = packet.getAddress(); int port = packet.getPort(); StringBuilder sb = new StringBuilder(); sb.append("服务器返回:"); sb.append(count++); sb.append(new String(bytes)); sb.append("呵呵"); byte[] res = sb.toString().getBytes(); DatagramPacket cpacket = new DatagramPacket(res,res.length,addr,port); socket.send(cpacket); } catch (IOException e) { e.printStackTrace(); } } } }
因为这个里面的bytes是有固定长度的,是1024,而读取时,读的最多也是1024光一个bytes的字符串就站满了,所以要修改,sb.append(new String(bytes).trim());这样就好了
Java Socket应用---通信是这样练成的
125013 学习 · 590 问题
相似问题