黑马程序员技术交流社区
标题:
Udp多线程自娱自乐
[打印本页]
作者:
vermouth
时间:
2015-1-19 11:26
标题:
Udp多线程自娱自乐
也是好久没写过网络编程,好累,写了一个小时。。。
/**
*/
import java.net.*;
import java.io.*;
class UdpChat{
public static void main(String [] args)throws Exception{
DatagramSocket send = new DatagramSocket();
DatagramSocket rec = new DatagramSocket(10007);
UdpSend us = new UdpSend(send);
UdpRec ur = new UdpRec(rec);
new Thread(us).start();
new Thread(ur).start();
}
}
class UdpSend implements Runnable{
private DatagramSocket ds = null;
public UdpSend(DatagramSocket ds){
this.ds = ds;
}
public void run(){
try{
DatagramPacket dp = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
byte [] buf = new byte[1024];
while ((line = br.readLine())!=null){
buf = line.getBytes();
dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("172.16.8.255"),10007);
ds.send(dp);
if(line.equals("over"))
break;
}
ds.close();
}
catch(Exception e){
throw new RuntimeException("rec ex");
}
}
}
class UdpRec implements Runnable{
private DatagramSocket ds = null;
public UdpRec(DatagramSocket ds){
this.ds = ds;
}
public void run(){
DatagramPacket dp = null;
byte [] buf = new byte[1024];
try{
while(true){
dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
int port = dp.getPort();
String data = new String(dp.getData(),0,dp.getLength()).trim();
if (data.equals("over")){
System.out.println("88");
}
else {
System.out.println("receive from:"+ip+".."+"port"+" : "+data);
}
}
}
catch(Exception e){
throw new RuntimeException("rec ex");
}
}
}
复制代码
我把close放在finally里抛出SocketException,可是提示我不能抛出,为甚么呢?
作者:
兮兮之c
时间:
2015-1-25 00:34
(1)你知道你为什么能抛出 RuntimeException然后没报错吗??(2)你把close放到finally中,会报SocketException,这是JDK的设计,然后这个异常是受检查异常,必须对其进行处理(要么就进行catch,要么声明throws),然后我觉得你肯定是使用了throws,这样就会出现问题,因为Runnable接口中的run方法没有抛出异常,这样就和重写的准则违背了,所以报错了
作者:
vermouth
时间:
2015-1-25 12:35
兮兮之c 发表于 2015-1-25 00:34
(1)你知道你为什么能抛出 RuntimeException然后没报错吗??(2)你把close放到finally中,会报SocketExc ...
我的意思是 开始把close写在finally 去catch了SocketException,但是编译不过 所以改成这样了
关于重写的问题 有点基础的都知道不可以那么写
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2