本帖最后由 25343215 于 2013-11-30 20:59 编辑
楼主的代码我修改了三个地方。后面有运行结果
都是在发送端,首先是BufferedReader的定义,还有String str=null,最后一个问题是客户端发送的数据包Ip地址里面,有错误。
具有见代码。
服务器端
- import java.io.*;
- import java.util.*;
- import java.net.*;
- public class UdpRece2 {
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- // TODO Auto-generated method stub
- try {
- DatagramSocket ds=new DatagramSocket(10066);
- while(true)
- {
- byte[] buf=new byte[1024];
- DatagramPacket dp=new DatagramPacket(buf,buf.length);
- ds.receive(dp);
- String data=new String(dp.getData(),0,dp.getLength());
- String ip=dp.getAddress().getHostAddress();
- int port=dp.getPort();
- System.out.println("IP"+ip);
- System.out.println("缓冲区数据是"+data);
- System.out.println("端口号"+port);
- }
- } catch (SocketException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- System.out.println("端口连接失败");
- }catch(IOException e)
- {
- e.printStackTrace();
- System.out.println("IO出现异常");
- }
-
- }
- }
复制代码 客户端:
- import java.io.*;
- import java.util.*;
- import java.net.*;
- public class UdpSend2 {
- /**
- * @param args
- * @throws IOException 2013/11/30
- */
- public static void main(String[] args)
- {
- BufferedReader br=null;
- try {
- br=new BufferedReader(new InputStreamReader(System.in));
- DatagramSocket ds=new DatagramSocket();
- String str=null;
- while ((str = br.readLine()) != null)
- {
- byte[] buf = str.getBytes();
- DatagramPacket dp = new DatagramPacket(buf,
- buf.length,
- InetAddress.getByName("192.168.1.101"),
- 10066);
- ds.send(dp);
-
- }
- ds.close();
- } catch (BindException e)
- {
- System.out.println("端口号已被占用");
- } catch(IOException e1)
- {
- System.out.println("读取数据失败");
- }
- try {
- br.close();
- } catch (IOException e2) {
- // TODO Auto-generated catch block
- e2.printStackTrace(System.out);
- System.out.println("关闭读取流失败");
- }
- }
- }
复制代码
|
|