JavaSE series code 73: Client program for UDP communication

Java RMI (remote method invocation) - Java’s remote method invocation is a unique distributed computing technology of Java. It allows the object running on one Java virtual machine to call the method of the object running on another Java virtual machine, so that Java programmers can easily do distributed computing in the network environment.
RMI defines a set of remote interfaces that can be used to generate remote objects. Clients can call remote objects with the same syntax as methods that call local objects. The classes and methods provided by the RMI API can handle the serialization of all basic communication and parameter reference requirements for accessing remote methods.

客户端程序代码:  
import java.net.*;
import java.io.*;
public class UDPClient
{
  public static void main(String[] args)
  {
    UDPClient frm=new UDPClient();
  }
  CliThread ct;         //声明客户类线程对象ct
  public UDPClient()    //构造方法
  {
    ct=new CliThread();   //创建线程
    ct.start();           //启动线程
  }
}
class CliThread extends Thread  //客户端线程类,负责发送信息
{
  public CliThread() {}     //构造方法
  public void run()
 {
    String str1;
    String servername="CGJComputer";    //服务器端计算机名
    System.out.println("请发送信息给服务器《"+servername +"》");
    try
    {
      DatagramSocket skt=new DatagramSocket();  //建立UDP socket对象
      DatagramPacket pkt;          //建立DatagramPacket对象pkt
      while(true)
      {
        BufferedReader buf;
        buf=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("请输入信息:");
        str1=buf.readLine();    //从键盘上读取数据
        byte[] outbuf=new byte[str1.length()];
        outbuf=str1.getBytes();
            //下面是取得服务器端地址
        InetAddress address=InetAddress.getByName(servername); 
        pkt=new DatagramPacket(outbuf,outbuf.length,address,8000);//数据打包
        skt.send(pkt);     //发送UDP数据报分组
      }
    }catch (IOException e) {}
  }
}

Published 73 original articles · praised 189 · 10,000+ views

Guess you like

Origin blog.csdn.net/blog_programb/article/details/105569683