本帖最后由 波涛 于 2014-5-27 12:35 编辑
下面是根据视频讲解中自己写的一个模拟聊天的简易控制台程序,编译时主方法中报“找不到合适的构造器错误”,求大神给予帮助!谢谢!
- /*
- 模拟简易聊天控制台程序
- */
- import java.io.*;
- import java.net.*;
- public class ChatDemo
- {
- public static void main(String[]args)
- {
- Send s = new Send();
- Recie r = new Recie();
- new Thread(s).start();
- new Thread(r).start();
- }
- }
- //接收类
- class Recie implements Runnable
- {
- public void run()
- {
- try
- { //创建接收服务Socket
- DatagramSocket dgs = new DatagramSocket(8081);
- //定义接收数组,并封装到包
- while(true)
- { byte buf[] = new byte[1024];
- DatagramPacket dp = new DatagramPacket(buf,buf.length);
- //调用服务的接收方法,接收数据
- dgs.receive(dp);
- //将接收到的数据拆包,得到想要的内容
- String ip = dp.getAddress().getHostAddress();
- String data = new String(dp.getData(),0,dp.getLength());
- System.out.println("IP:"+ip+" 消息:"+data);
- //关闭资源
- //dgs.close();
- }
- }catch(Exception e){System.out.println(e.toString());}
- }
- }
- //发送类
- class Send
- {
- public void run()
- {
- //定义服务
- DatagramSocket ds = new DatagramSocket();
-
- //接收用户键盘录入,转为字节包装后发送到指定ip和端口上,
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String line = null;
- DatagramPacket dp = null;
-
- while((line=br.readLine())!=null)
- {
- if("886".equals(line))
- break ;
- try
- {
- dp = new DatagramPacket(line.getBytes(),line.length(),InetAddress.getByName("192.168.0.101"),8081);
- }
- catch (Exception e)
- {
- System.out.println(e.toString());
- }
-
- //调用服务的发送功能,将数据包发送出去
- ds.send(dp);
- }
- }
- }
复制代码
|
|