本帖最后由 bird_not_fat 于 2013-10-14 20:47 编辑
接收端:- import java.io.IOException;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- /**
- * 示例:应用UDP协议的Socket接收端示例
- * @author lt
- */
- public class UDPReceiveDemo {
- public void receiveData() throws SocketException,UnknownHostException,IOException{
- //创建一个指定端口和IP的UDP码头,不写在while中防止出现bindException
- DatagramSocket ds = new DatagramSocket(50000,InetAddress.getLocalHost());
- while(true){
- //创建一个数据包对象用于接收数据包
- byte[] bt = new byte[1024];
- DatagramPacket dp = new DatagramPacket(bt,bt.length);
- //通过receive方法接收数据包
- ds.receive(dp);
- //获取数据包中的信息,发送的时候封装了InetAddress对象,端口号,字符串
- int port = dp.getPort();//发送端的端口号
- InetAddress ia = dp.getAddress();//发送端的IP地址
- byte[] getByte = dp.getData();
- int length = dp.getLength();
- String getByteStr = new String(getByte,0,length);
- System.out.println(port + " " + ia.getHostAddress() + " " +
- length + " " + getByteStr);
- }
- }
- public static void main(String[] args) {
- try {
- new UDPReceiveDemo().receiveData();
- } catch (SocketException e) {
- System.out.println("创建DatagramSocket出现异常。");
- } catch (UnknownHostException e) {
- System.out.println("未知主机异常。");
- } catch (IOException e) {
- System.out.println("接收数据包时发生异常。");
- }
- }
- }
复制代码 发送端:- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- import java.net.UnknownHostException;
- /**
- * 示例:键盘输入的方式向服务器发送信息
- * @author lt
- */
- public class UDPSendKeyboardDemo {
- public void sendDataByKeyboard() throws SocketException,UnknownHostException,IOException{
- //可以制定一个发送端的端口
- DatagramSocket ds = new DatagramSocket();
- InputStream is = System.in;
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- String str = null;
- while((str = br.readLine())!=null){
- if("88".equals(str)){
- break;
- }
- DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length(),
- InetAddress.getLocalHost(),50000);
- ds.send(dp);
- }
-
- if(ds != null){
- ds.close();
- }
-
- }
- public static void main(String[] args) {
- try {
- new UDPSendKeyboardDemo().sendDataByKeyboard();
- } catch (SocketException e) {
- System.out.println("数据报Socket创建时发生异常。");
- } catch (UnknownHostException e) {
- System.out.println("未知主机异常。");
- } catch (IOException e) {
- System.out.println("发送数据包异常。");
- }
- }
- }
复制代码 我在发送端输入中文,比如 "黑马程序员",在服务器端只能收到 "50057 115.27.28.77 5 黑马?" 即为中文字符只能收到一半,为什么只能接收到一半??
我改成DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length() * 2,
InetAddress.getLocalHost(),50000);就能接收到完整中文字符了,这是为什么呢????
|