/*
* 编写一个聊天程序,有售数据的部分和发数据的部分。
* 这两部分需要同时执行。
* 那就需要多线程技术,一个控制收,一个控制发
*
* 因为接收和发送动作是不一致的,所以要定义两个run方法,
* 而且这两个方法要封装到不同的类中。
*/
package test.itheima;
import java.io.*;
import java.net.*;
class Send implements Runnable {
private DatagramSocket ds = null;
Send(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
BufferedReader bf = null;
try {
bf = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while (((line = bf.readLine()) != null)) {
if ("over".equals(line))
break;
byte[] b = line.getBytes();
DatagramPacket d = new DatagramPacket(b, b.length,
InetAddress.getByName("127.0.0.1"), 10002);
ds.send(d);
}
} catch (IOException e) {
e.printStackTrace();
ds.close();
}
}
}
class Recieve implements Runnable {
private DatagramSocket ds = null;
Recieve(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
DatagramPacket dp = null;
byte[] data = new byte[1024];
while (true) {
try {
dp = new DatagramPacket(data, data.length);
ds.receive(dp);
data = dp.getData();
String ip = dp.getAddress().getHostAddress();
//byte[] otherip = dp.getAddress().getAddress();
int port = dp.getPort();
int localport = ds.getLocalPort();
System.out.println("Remote:" + ip + "[" + port + "] : "
+ (new String(data, 0, data.length)));
System.out.println("Locle :" + (new String(ip)) + "[" + localport
+ "] : " + (new String(data, 0, data.length)));
System.out.println("-------------- new line ----------------");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class ChartDemo {
public static void main(String[] args) throws SocketException {
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receiveSocket = new DatagramSocket(10002);
new Thread(new Send(sendSocket)).start();
new Thread(new Recieve(receiveSocket)).start();
}
}
[黑马程序员]chartdemo
最新推荐文章于 2022-10-11 18:10:23 发布