JavaSE series code 74: Server-side program for UDP communication

RMI is tightly integrated with Java language, which can provide very good fault tolerance and exception handling compared with CORBA
RMI is the basic model of Java language in distributed computing. Many Java distributed systems, including the EJB we are going to cover in this chapter, are built on the idea of RMI.

服务器端程序代码: 
import java.net.*;
import java.io.*;
public class UDPServer
{
  public static void main(String[] args)
  {
    UDPServer frm=new UDPServer();
  }
  String strbuf= " ";
  SerThread st;        //声明服务器类线程对象st
  public UDPServer()
  {
    st=new SerThread();     //创建线程
    st.start();             //启动线程
  }
}
class SerThread extends Thread   //服务器类线程,负责接收信息
{
  public SerThread() {}   //构造方法
  public void run()
 {
    String str1;
    try
    {      //使用8000端口,建立UDP Socket对象
      DatagramSocket skt=new DatagramSocket(8000); 
      System.out.print("服务器名:");
           //显示服务器计算机的名称
      System.out.println(InetAddress.getLocalHost().getHostName());
      while(true)
      {
        byte[] inbuf=new byte[256];
             //下面是取得服务器端地址
        DatagramPacket pkt;
            //创建并设置接收pkt对象的接收信息
        pkt=new DatagramPacket(inbuf,inbuf.length); 
        skt.receive(pkt);  //接收数据报分组
            //提取接收到的分组中的数据并转成字符串
        str1=new String(pkt.getData());
        str1=str1.trim();      //去掉字符串中的首尾空格
        if(str1.length()>0)
        {
          int pot=pkt.getPort();    //获取远程端口号
          System.out.println("远程端口:"+pot);
          System.out.println("服务器已接收到信息:"+str1);
        }
      }
    }catch (IOException e) { return;  }
  }
}
Published 73 original articles · praised 189 · 10,000+ views

Guess you like

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