[問題] 簡單的UDP程式一直報錯
大家好,是這樣的,我想寫一個簡單的UDP client/server程式,參考過網上很多範例,不過一直卡在某個環節讓我無法進行下去,以下是程式:
Client端:每秒會送出一個時間封包給Server端,總共送十個封包
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException{
SocketAddress addr = new InetSocketAddress("192.168.1.100", 8888);
for(int i=0; i<=10; i++){
Long client_time = System.currentTimeMillis();
byte[] bdata = client_time.toString().getBytes();
DatagramPacket pack = new DatagramPacket(bdata, bdata.length, addr);
DatagramSocket dest = new DatagramSocket();
dest.send(pack);
try{
Thread.sleep(1000);
}catch(Exception e){
System.out.println(e);
}
}
}
}
Server端:接收Client端的時間封包,並將「Server端這邊收到封包當下的時間」與「封包內Client端那邊的時間」相減
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException{
byte[] buffer = new byte[50];
DatagramPacket pack = new DatagramPacket(buffer, buffer.length);
DatagramSocket dest = new DatagramSocket(8888);
while(true){
System.out.println("等待封包傳進"+dest.getLocalPort());
dest.receive(pack);
long server_time = System.currentTimeMillis();
String data = new String(pack.getData());
try{
long client_time = Long.valueOf(data); //錯誤的地方
//System.out.println(client_time);
long difference = server_time - client_time;
System.out.println(difference);
} catch(NumberFormatException e){
System.out.println(e);
}
}
}
}
錯誤在這一行:long client_time = Long.valueOf(data);
每當要執行這一行時就會遇到「NumberFormatException」這個例外。
我查過原因大概是,將字串轉成長整數時,字串內有包含「非數字」才會導致出錯,可是我將client_time印出來的確都是數字,實在看不出哪裡有錯...卡這邊卡了一個下午...
另外Long.parseLong()這方法也試過了還是不行
我的環境是Mac OSX,Client跟Server的程式都只在同一台機子上跑而已,有請版友幫忙提點一下,感謝...
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.118.155.43
※ 文章網址: https://www.ptt.cc/bbs/java/M.1422876120.A.112.html
※ 編輯: liataian (140.118.155.43), 02/02/2015 19:27:00
※ 編輯: liataian (140.118.155.43), 02/02/2015 19:31:12
→
02/02 19:35, , 1F
02/02 19:35, 1F
→
02/02 19:35, , 2F
02/02 19:35, 2F
→
02/02 19:36, , 3F
02/02 19:36, 3F
→
02/02 19:37, , 4F
02/02 19:37, 4F
→
02/02 19:38, , 5F
02/02 19:38, 5F
→
02/02 19:38, , 6F
02/02 19:38, 6F
→
02/02 19:39, , 7F
02/02 19:39, 7F
→
02/02 19:40, , 8F
02/02 19:40, 8F
→
02/02 19:42, , 9F
02/02 19:42, 9F
→
02/02 19:43, , 10F
02/02 19:43, 10F
→
02/02 23:10, , 11F
02/02 23:10, 11F