⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 udpclientdemo.java

📁 联系方式 lovely2000@sina.com
💻 JAVA
字号:
/*
 * UDPClientDemo.java
 *
 * Created on 2007年11月13日, 下午9:13
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package happychat;
import java.net.*;
import java.io.*;
/**
 *基于UDP的客户端程序
 * @author fan
 */
public class UDPClientDemo {
    static final int PORT = 4000;
    private DatagramSocket s;
    private InetAddress hostAddress;
    private byte[] buf = new byte[1000];
    private DatagramPacket dp = new DatagramPacket(buf,buf.length);
    
    /** Creates a new instance of UDPClientDemo */
    public UDPClientDemo() {
        try{
            s = new DatagramSocket();
            hostAddress = InetAddress.getByName("localhost");
            System.out.println("Client start......");
            while(true){
                String strOutMess = "";
                BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
                try{
                    strOutMess = stdin.readLine();
                }catch(IOException ie){
                    System.out.println("IO error");
                }
                if(strOutMess.equals("bye")) break;
                String strOut = "[Client say]: "+strOutMess;
                byte[] buf = strOut.getBytes();
                DatagramPacket out = new DatagramPacket(buf,buf.length,4000);
                s.send(out);
                s.receive(dp);
                String strReceived = "("+dp.getAddress()+":"+dp.getPort()+")"+new String(dp.getData(),0,dp.getLength());
                System.out.println(strReceived);
                
                }
            }catch(UnknownHostException e){
                System.out.println("未找到服务器!");
                System.exit(1);
        }catch(SocketException e){
            System.out.println("打开套接字错误!");
            e.printStackTrace();
            System.exit(1);
        }catch(IOException e){
            System.err.println("数据传输错误!");
            e.printStackTrace();
            System.exit(1);
        }
    }
    public static void main(String []args){
        new UDPClientDemo();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -