客戶端不能將接收到信息完全打印出來,請(qǐng)問是怎么回事呢?(客戶端顯示在代碼后)
/* *UDP服務(wù)端 */
package com.imooc;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPserver {
UDPserver() throws IOException{
DatagramSocket ds = new DatagramSocket(5555);
byte[] b = new byte[2048];
DatagramPacket dp = new DatagramPacket(b,0,b.length);
ds.receive(dp);
String s = new String(b);
System.out.println("我是服務(wù)器,客戶端說: "+s);
InetAddress address = InetAddress.getByName("localhost");
int port = dp.getPort();
byte[] b1 = new byte[2048];
b1= "客戶端你好,你的信息已經(jīng)收到,我是服務(wù)器".getBytes();
DatagramPacket dp2 = new DatagramPacket(b1,0,b1.length,address,port);
ds.send(dp2);
ds.close();
}
public static void main(String[] args) throws IOException {
UDPserver us = new UDPserver();
}
}
/*
*UDP客戶端
*/
package com.imooc;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
public class UDPclient {
public static void main(String[] args) throws IOException{
DatagramSocket ds = new DatagramSocket();
InetAddress address = InetAddress.getByName("localhost");
int port = 5555;
byte[] b = new byte[2048];
b ="用戶名:1;密碼:2".getBytes();
DatagramPacket dp = new DatagramPacket(b,b.length,address,port);
ds.send(dp);
DatagramPacket dp1 = new DatagramPacket(b,b.length);
ds.receive(dp1);
String s1 = new String(b);
System.out.println("我是客戶端,服務(wù)器說: ?"+s1);
ds.close();
}
}
客戶端打?。?br />
客戶端你好,你?
2016-10-25
你前面那個(gè)服務(wù)器端的代碼都沒有放到main方法里去。
UDPserver us = new UDPserver();
你用的這種方式根本就不能夠調(diào)用上面的那些方法,因?yàn)檫@個(gè)是創(chuàng)建實(shí)例對(duì)象......而你想要的是運(yùn)用那些方法。
2016-07-06
接受客戶端信息時(shí):String s1 = new String(b);應(yīng)該修改為String s1 = new String(b,0,dp1.getLength());
2016-04-27
byte[] b = new byte[2048];
b ="用戶名:1;密碼:2".getBytes();
byte[] b1 = new byte[2048];
b1= "客戶端你好,你的信息已經(jīng)收到,我是服務(wù)器".getBytes();
你分別給b和b1都賦值了,所以他們的長(zhǎng)度都改變了,當(dāng)你用b來接受b1時(shí),由于b的長(zhǎng)度比b1短,所以接收不完。
2016-02-02
System.out.println("我是服務(wù)器,客戶端說: "+s);
InetAddress address = InetAddress.getByName("localhost");
int port = dp.getPort();
address 弄粗了,應(yīng)該發(fā)往的地址是?InetAddress address = packet.getAddress();