本帖最后由 joure 于 2014-1-6 17:19 编辑
如题:UDP编程:发送端DatagramPacket设置为广播地址192.168.1.255时接收端可以正常接收;设置成LocalHost地址127.0.0.1时也正常,但是当设置成其它IP时接收端就无法接收数据
- import java.net.*;
- import java.io.*;
- class UdpSend2
- {
- public static void main(String[] args) throws Exception
- {
- DatagramSocket ds = new DatagramSocket(); //创建发送端
- BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));//键盘录入
- String line = null;
- while ((line=bufr.readLine()) !=null)//阻塞式方法read
- {
- if("886".equals(line))
- break;
- byte[] buf = line.getBytes();//字节数组 封包
- DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.110"),10086);
- ds.send(dp); //发送
- }
- ds.close();
- }
- }
- class UdpRec
- {
- public static void main(String[] args) throws Exception
- {
- DatagramSocket ds = new DatagramSocket(10086); //创建接收端
- while (true)
- {
- byte[] buf = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf,buf.length);//将接收的数据封包
- ds.receive(dp);//阻塞式方法
- String ip = dp.getAddress().getHostAddress();
- String data = new String(dp.getData(),0,dp.getLength());
- System.out.println(ip+" : "+data);
- }
- }
- }
复制代码 在TCP编程时也遇到了这种问题,服务端无法接受客户端的数据,等待5秒抛异常Exception in thread "main" java.net.ConnectException: Connection timed out: connect
- import java.net.*;
- import java.io.*;
- class TcpClient
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket("192.168.1.254",10005);
- OutputStream out = s.getOutputStream();
- out.write("TCP is coming".getBytes());
- s.close();
- }
- }
复制代码- class TcpServer
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss = new ServerSocket(10005);
- Socket s = ss.accept(); //该阻塞式方法获取到客户端对象
- String ip = s.getInetAddress().getHostAddress();
- System.out.println(ip+"...connected");
- InputStream in = s.getInputStream();
- byte[] buf = new byte[1024];
- int len = in.read(buf);
- System.out.println(new String(buf,0,len));
- s.close(); //关闭客户端,节省资源
- ss.close(); //关闭服务端(可选)
- }
- }
复制代码
找来毕老师的源码运行了一下,问题依旧
系统Win7 64位,JDK1.7,防火墙关了
求解决方法,不胜感激!
|