UDP 및 배열 관련 toString 방법

2245 단어 toStringUDP
public class chatDialog {

	public static void main(String[] args) throws Exception, IOException {
		System.out.println("     :");
//		System.out.println(InetAddress.getByName("download.filesfrog.com")
//				.getHostAddress());
		
//		byte[] buf = {1,1,2,2,3,2};
//		System.out.println(new String(buf));
//		System.out.println(Arrays.toString(buf));
//		System.out.println(buf.toString());
		
		DatagramSocket ds = new DatagramSocket(1233);
		new Thread(new receive(ds)).start();
		//     IP
		InetAddress ia = InetAddress.getByName("yun-pc");//yun-pc  localHost 127.0.0.1       
		new Thread(new send(ia)).start();
	}

}
class receive implements Runnable{
	DatagramSocket ds ;
	public receive(DatagramSocket ds) {
		super();
		this.ds = ds;
	}
	public void run() {
		try {
			while (true) {
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				ds.receive(dp);
				//                  IP          IP127.0.0.1
				String IP = dp.getAddress().getHostAddress();
				byte[] get = dp.getData();
				System.out.println(IP + ":\r
" + new String(get)); } } catch (Exception e) { e.printStackTrace(); } } } class send implements Runnable{ InetAddress ia; private DatagramSocket s; send(InetAddress ia){ this.ia = ia; } public void run() { try { s = new DatagramSocket(); while (true) { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String line = br.readLine(); byte[] buf = line.getBytes(); DatagramPacket dp = new DatagramPacket(buf, buf.length, ia, 1233); s.send(dp); } } catch (Exception e) { e.printStackTrace(); } } }

배열을 문자열 바이트 배열로 변환하는 방법은 new String(byte[],start,end) 하나뿐입니다.
문자 배열에는 두 가지 new String(char[], start, end)과 String이 있습니다.valueOf(char[] 이름);
배열 도구 클래스 Arrays의 toString(byte[]) 방법 및 배열 자체의 toString() 방법
System.out.println(Arrays.toString("안녕하세요.getBytes()));//[-60, -29, -70, -61]
byte[] buf = {-60, -29, -70, -61};
System.out.println(new String(buf));//안녕하세요.
System.out.println(Arrays.toString(buf));//[-60, -29, -70, -61]
System.out.println(buf.toString());//[B@15bdc50

좋은 웹페이지 즐겨찾기