黑马程序员--Java之网络编程11

——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-

黑马程序员–Java之网络编程11

一、网络通信

  1. IP地址:网络中设备的标识,可以通过主机名获取,本地回路:127.0.0.1,未与网上绑定,可实现本地网络程序之间通讯
  2.  端口号:用于标识进程的逻辑地址,即标识不同的进程,有效端口 0~65535,其中 0~1023是系统使用或者知名网络应用和服务
  3.  传输协议:通信规则,分TCP和UDP两种协议。

二、UDP

  1. 面向无连接,将数据和源及目的地址封装在数据包之中
  2. 是不可协议
  3. 不需要建立连接,速度快
  4. 每个数据包的大小限制在64K内
    接收端程序:
import java.net.*;
public class Rece{
    public static void main(String[] args){
        byte[] buf = new byte[1024];
        //创建一个长度为1024的字节数组,用于接收数据
        //定义一个DatagramSocket对象,监听的商品号为8954
        DatagramSocket ds = new DatagramSocket(8954);
        //定义一个DatagramPacket对象,用于接收数据
        DatagramPacket dp = new DatagramPacket(buf,1024);
        System.out.println("等待接收数据");
        ds.recevie(dp);//等待接收数据,如果没有数据则会阻塞
        //调用DatagramPacket的方法获得接收的信息
        String str = new String(dp.getData(),0,dp.getLength())+
            "form" + dp.getAddress().getHostAddress() +
            ":" + dp.getPort();
            System.out.println(str);
            ds.close();//释放资源
    }
}       

发送端程序:

import java.net.*;
public class Send{
    public static void main(String[] args){
        //创建一个DatagramSocket对象
        DatagramSocket ds = new DatagramSocket();
        String str = "Hello world!";
/*创建一个要发送的数据包,包括发送数据,数据长度,接收端IP以及端口号*/
        DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length(),
            InetAddress.getByName("localhost"),8954);
        System.out.println("发送信息");
        ds.send(dp);//发送数据
        ds.close();//释放资源
    }
}

同时具备发送接收的聊天室:

import java.io.*;
import java.net.*;
public class UdpChat {
    public static void main(String[] args) throws Exception {
        DatagramSocket sendSocket = new DatagramSocket();
        DatagramSocket receSocket = new DatagramSocket(5461);
        new Thread(new Send(sendSocket)).start();
        new Thread(new Rece(receSocket)).start();
    }

}
class Send implements Runnable {
    private DatagramSocket ds;  
    public Send(DatagramSocket ds){
        this.ds = ds;
    }   
    public void run(){
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while((line = br.readLine()) != null){
                if(line == "886"){
                    break;
                }
                byte[] buf = new byte[1024];
                buf = line.getBytes();
                DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.110"),5460);
                ds.send(dp);    
            }
        } catch (Exception e) {
            throw new RuntimeException("发送失败!");
        }
    }   
}

class Rece implements Runnable {
    private DatagramSocket ds;  
    public Rece(DatagramSocket ds){
        this.ds = ds;
    }   
    public void run(){
        try {
            while(true){
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf,buf.length);         
                ds.receive(dp);
                String info = dp.getAddress().getHostAddress() + ":" + dp.getPort();
                String data = new String(dp.getData(),0,dp.getLength());
                System.out.println("Messages from " + info + "<--" + data);
            }
        } catch (IOException e) {
            throw new RuntimeException("接收失败!");
        }

    }
}

三、TCP

  1. Socket和ServerSocket
  2. 建立客户端和服务器端
  3. 建立连接后,通过Socket的IO流传输数据
  4. 关闭Socket
  5. 客户端和服务器端是两个独立的应用程序
    Socket 类 :是实现客户端的套接字
    • Socket();
    • Socket(InetAddress address, int port); //创建一个套接字连接到一个指定的IP地址和端口。
      示例:客户端:服务端点,并读取客户端已存在的图片数据。通过socket 输出流将数据发送给服务器端读取服务器端的反馈之后关闭
import java.io.*;
import java.net.*;
class PicClient{
   public static void main(String[] args) throw Exception{
      Socket s =new Socket("192.168.1.110",5460);
      FileInputStream fis =new FileInputStream("1.bmp");
      OutputStream out=s.getOutputStraem();
      byte[] buf=new byte[1024];
      int len =0;
      while((len=fis.read(buf))!=-1){   
      //客户端读到-1时停止,返回-1前的数据,所以服务器端不会停止
        out.write(buf,0,len);
      }
      s.shutdownOutput);
      InPutStream in =s.getInputStream();
      byte[] bufIn= new byte[1024];
      int num=in.read(bufIn);
      System.out.println(new String(bufIn,0,num);
      fis.close();
      s.close();
   }
 }
 class PicServer{
   public static void main(String[] args) throw Exception{
        ServerSocket ss=new ServerSocket(5460);
        Socket s=ss.accept();
        InputSteam in=s.getInputStream();
        FileOutputStream fos=new FileOutputStream("Sever.bmp");
        int len =0;
        while((len=in.read(buf))!=-1){
            fos.write(buf,0,len);
        }
        OutputStream out =s.getOutputStream();
        out.write("上传成功".getBytes());
        fos.close();
        s.close();
        ss.close();
   }
 }

多线程的TCP网络程序:
服务器端为每一个客户端封装到一个单独的线程中,这样就可以同时处理多个客户端 ,只要明确了每一个客户端在服务器端。

import java.net.*;
import java.io.*;
class PicThread implements Runnable{
    private Sockte s;
    picThread(Socket s){
       this.s=s;
    }
    public void run(){
        String ip= s.getInetAddress().getHostAddress();
        try{

             System.out.println(ip+"...connecting"); 
             FileOutputStream fos=new FileOutputStream("Sever.bmp");

             int len =0;
              while((len=in.read(buf))!=-1){
               fos.write(buf,0,len);
              }
              OutputStream out =s.getOutputStream();
              out.write("上传成功".getBytes());
              fos.close();
              s.close();
        }
        catch(Exception e){
        throw new RuntimeException(ip+"上传失败");
    }
 }
 class PicServer{
   public static void main(String[] args) throw Exception{
        ServerSocket ss=new ServerSocket(5460);
        while(true){
        Socket s=ss.accept();
        new Thread(new PicThread(s)).start();
        }
    }
 }   
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值