[問題] UDP無限等待發生例外

看板java作者 (Lucifer)時間16年前 (2009/03/18 15:58), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串1/1
各位:   我用java內建的DatagramSocket和DatagramPacket寫了個簡單的msger   但遇到些問題.   首先是我用while(true)去監聽receive會出現 java.net.BindException: Address already in use: Cannot bind   這個例外.   另外就是傳送中文字會出現亂碼或是尾巴就不見了O_Q   請問是什麼問題呢? 抱歉, 我找到中文的問題了Orz 中文OK的程式碼: public static void send(String IP, String msg) { try { DatagramSocket socket = new DatagramSocket(1254); InetAddress ip = InetAddress.getByName(IP); byte msg_byte[] = msg.getBytes("UTF-8"); //keypoint DatagramPacket dp = new DatagramPacket(msg_byte, msg_byte .length, ip, 90); socket.send(dp); } catch (Exception e) { System.out.println("method send occurrence error: " + e); } } public static String receive() { try{ DatagramSocket socket = new DatagramSocket(90); byte msg[] = new byte[1026]; String result = ""; DatagramPacket dp = new DatagramPacket(msg, msg.length); socket.receive(dp); byte tmp[] = new byte[dp.getLength()]; for (int j = 0; j < tmp.length; j++) { tmp[j] = dp.getData()[j]; } System.out.println(new String(tmp, "UTF-8")); return new String(tmp, "UTF-8"); } catch (Exception e) { System.out.println("method receive occurrence error: " + e); return null; } }   但是例外我還是不知道啊啊啊Orz -- 重要的是"心" -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.64.129.167 ※ 編輯: zeat 來自: 203.64.129.167 (03/18 16:23) ※ 編輯: zeat 來自: 203.64.129.167 (03/18 16:23)

03/18 17:53, , 1F
同一個 port 的 socket bind 只能建立一次 否則失敗。
03/18 17:53, 1F

03/18 18:04, , 2F
感謝, 問題解決了= =+
03/18 18:04, 2F
文章代碼(AID): #19mAd1j_ (java)