首页 > Java > java教程 > Java之网络编程实例详解

Java之网络编程实例详解

零下一度
发布: 2017-07-24 09:22:52
原创
1836 人浏览过

一、套接字 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();
                                }
                            }
登录后复制

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

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);    
                            }
                    }
                }
登录后复制

 例三:多线程聊天室程序

 

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之网络编程实例详解的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板