毕老师视频中的UDP聊天小程序是将对方的IP地址写死的,我想可不可以在dos命令行下第一行输入对方IP地址,选择聊天对象后开始聊天呢?做了些小改动实现了一个小小的需求。代码经过实践检验,局域网条件下可以在DOS窗口运行该程序实现通过第一行输入对方IP地址进行选择聊天对象聊天。- package p2;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.SocketException;
- public class UDP_ChatDemo {
-
- public static void main(String[] args) throws SocketException {
- DatagramSocket send = new DatagramSocket(7778);
- DatagramSocket rece = new DatagramSocket(10004);
-
- new Thread(new Send_1(send)).start();
- new Thread(new Rece_1(rece)).start();
- }
- }
- //创建发送任务
- class Send_1 implements Runnable{
- //持有UDP套接字
- private DatagramSocket socket;
- /**
- * @param socket
- */
- public Send_1(DatagramSocket socket) {
- super();
- this.socket = socket;
- }
- @Override
- public void run() {
- try {
- //创建键盘读取流
- BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
- //第一行读取输入的对方ip地址
- String ip = bfr.readLine();
- //读取聊天数据
- String line = null;
- while ((line=bfr.readLine())!=null) {
- if("over".equals(line))
- break;
- byte[] buf = line.getBytes();
- //创建数据包对象
- DatagramPacket packet = new DatagramPacket(buf, 0, buf.length,InetAddress.getByName(ip), 10004);
- //发送数据
- socket.send(packet);
- }
- bfr.close();
- } catch (IOException e) {
- }
-
- }
-
- }
- //创建接收任务
- class Rece_1 implements Runnable{
- //持有UDP套接字
- private DatagramSocket socket;
- /**
- * @param socket
- */
- public Rece_1(DatagramSocket socket) {
- super();
- this.socket = socket;
- }
- @Override
- public void run() {
- try {
- //创建缓冲数组
- byte[] buf = new byte[1024];
- //创建数据包对象
- DatagramPacket packet = new DatagramPacket(buf, buf.length);
- while (true) {
- //接收数据包
- socket.receive(packet);
- //获取数据
- byte[] data = packet.getData();
- //控制台输出
- String text = new String(data,0,packet.getLength());
- String ip = packet.getAddress().getHostAddress();
- System.out.println(ip+"::"+text);
- }
- } catch (IOException e) {
- }finally{
- socket.close();
- }
-
- }
-
- }
复制代码
|
|