欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  Java

Java之网络编程实例详解

程序员文章站 2022-04-13 20:53:10
...
一、套接字 Socket

网络驱动程序提供给应用程序编程的接口和一种机制,可以比喻成一个港口码头 应用程序只要把货放在这,就算完成了货物的运送。它在应用程序中创建,通过一种绑定机制与驱动程序建立关系,告诉自已对应的IP 和 Port。

Socket是 java 中网络编程的类 , 位于java.net包中。

---- DatagramSocket //用于UDP通迅

---- ServerSocket //用于TCP通讯,用于服务端

---- Socket //用于Tcp通讯的服务端和客户端

二、UDP 网络程序

InetAddress 类 表示互联协议(IP)地址

//static InetAddress getLocalHost() throws UnknownHostException 返回本地主机

//static InetAddress getByName(String host) 在给定主机名的情况下确定主机的 IP 地址。 主机名可以是机器名
//(如 "java.sun.com"),也可以是其 IP 地址的文本表示形式

//static InetAddress[] getAllByName(String host) 根据主机名返回其 IP 地址所组成的数组。

static void ipDemo() throws UnknownHostException{
                InetAddress netAddr=InetAddress.getLocalHost();                //取得本地电脑的一些信息System.out.println(netAddr.toString());  
                System.out.println(netAddr.getHostAddress());
                System.out.println(netAddr.getHostName()); //取得其他电脑的信息InetAddress netAddr2=InetAddress.getByName("DELL-PC");  //这里也可以传IP地址System.out.println(netAddr2.getHostAddress());  //169.254.170.71System.out.println(netAddr2.getHostName()); //DELL-PC                //取得百度的地址InetAddress []  ipList=InetAddress.getAllByName("www.baidu.com");for(InetAddress addr:ipList){
                    System.out.println(addr.toString()); 
                }
            }

三、UDP发送和接收 DatagramSocket , DatagramPacket

//例一 最简的发送和接收

发送端==要导java.net包

通过UDP的方式把数据发出去:

1) 建立UDPSocket服务

2) 提供数据,将数据封装到数据包中 DatagramPacket (byte[] buf, int length, InetAddress address, int port) //构造函数有多个

3) 通过Socket服务,发送数据

4) 关闭资源

import java.net.*;class Sender4{//DatagramPacket (byte[] buf, int length, InetAddress address, int port) public static void main(String [] args) throws Exception
                                {                                      byte [] buff="hello cat".getBytes(); 
                                        DatagramSocket socket=new DatagramSocket();
                                        DatagramPacket packet=new DatagramPacket(buff,buff.length,InetAddress.getByName("192.168.0.103"),8888);
                                        socket.send(packet);
                                        socket.close();
                                        System.out.println("ok");
                                }
                            }

--接收端

1) 创建Socket服务,指定在某个端口上监听

2) 创建一个用于接收数据的 DatagramPacket

3) 从包中取出数据

4) 关闭资源

import java.net.*;class Receive4
                            {public static void main(String [] args) throws Exception
                                {
                                DatagramSocket socket=new DatagramSocket(8888); //别忘了端口号byte[] buff=new byte[1024] ;
                                    DatagramPacket packet=new DatagramPacket(buff,buff.length);
                                    
                                    socket.receive(packet);
                                    
                                    String senderIp=packet.getAddress().getHostAddress();
                                    String senderData=new String(packet.getData(),0,packet.getLength());int senderPort=packet.getPort();
                                    System.out.println(senderIp+"---"+senderData+"---"+senderPort);
                                    
                                    socket.close();
                                }
                            }

Java之网络编程实例详解

//例二,循环的发送和接收

import java.net.*;import java.io.*;class NewSender{public static void main(String [] args) throws Exception
                        {
                                System.out.println("发送端启动了");
                                DatagramSocket socket=new DatagramSocket();
                                
                                BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //包装键盘输入流String str=null;while((str=br.readLine())!=null){byte [] buff=str.getBytes();
                                        DatagramPacket packet=new DatagramPacket(buff,buff.length,InetAddress.getByName("127.0.0.1"),9000);
                                        socket.send(packet);
                                }
                                
                                br.close();
                                socket.close();            
                        }    
                    }
import java.net.*;class NewReceiver{public static void main(String [] args) throws Exception
                    {
                            DatagramSocket socket=new DatagramSocket(9000);
                            System.out.println("接收端启动了");                            while(true){ 
                                  byte [] buff=new byte[1024] ; 
                                  DatagramPacket packet=new DatagramPacket(buff,buff.length);
                                  socket.receive(packet);
                                  
                                  String senderIp=packet.getAddress().getHostAddress();                                  int sendPort=packet.getPort();
                                  String msg= new String(packet.getData(),0,packet.getLength());
                                  
                                  System.out.println(senderIp+":"+sendPort+":"+msg);    
                            }
                    }
                }

Java之网络编程实例详解

例三:多线程聊天室程序

class Chat
        {public static void main(String [] args)
                {new Thread(new SendThread()).start(); new Thread(new ReceiveThread()).start(); 
                }
        }
//发送端import java.io.*;import java.net.*;class SendThread implements Runnable
        {              private DatagramSocket socket;public void run()
                {try{
                        socket=new DatagramSocket();
                        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                        String msg=null;while((msg=br.readLine())!=null){byte[] buff=msg.getBytes();
                            DatagramPacket packet=new DatagramPacket(buff,buff.length,InetAddress.getByName("127.0.0.1"),10000);
                            socket.send(packet);
                        }
                        
                        socket.close();
                        br.close();
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                }
        }
//接收端import java.net.*;class ReceiveThread implements Runnable{    private DatagramSocket socket;                    public void run(){try{
                        socket=new DatagramSocket(10000);while(true){byte [] buff=new byte[1024];
                            DatagramPacket packet=new DatagramPacket(buff,buff.length);
                            socket.receive(packet);
                            
                            String senderIp=packet.getAddress().getHostAddress();int senderPort=packet.getPort();
                            String msg=new String(packet.getData(),0,packet.getLength());
                            
                            System.out.println(senderIp+":"+senderPort+":"+msg);
        
                        }
                    }catch(Exception ex)
                    {
                        System.out.println(ex.getMessage());
                    }
                }    
        }

Java之网络编程实例详解

以上就是Java之网络编程实例详解的详细内容,更多请关注其它相关文章!