java socket编程

  • Tcp/ip、udp
  • Url
Tcp/ip编程

通过三次握手完成连接,是可靠协议,必须建立连接,效率会稍低。java中通过socket套接字实现C/S通信。

 //Tcp/ip 服务端
public static void main(String[] args) {
    System.out.println("服务端启动成功");
     try { 
    System.out.println("等待客户端呼叫");
    ServerSocket serverSocket=new ServerSocket(8888);
      while(true){
      Socket socket=serverSocket.accept();  
      new T1(socket).start();
      System.out.println("服务端启动结束");
     }  
} catch (IOException e) {
    e.printStackTrace();
}   
  }
   }
  • 服务器端:
  • 创建ServerSocket对象(并绑定端口)
  • 调用accept方法,等待来自客户端的连接
  • 调用getInputStream/getOutputStream方法,进行I/O
  • 关闭Socket

    因为服务端要为多个客户端同时启动,所以要用到多线程

        //线程
        public class T1 extends Thread {
        public T1(Socket socket) {
    super();
     this.socket = socket;
           }
           Socket socket;
           @Override
           public void run() {
     InputStream in;
    try {
          in = socket.getInputStream();
          OutputStream out=socket.getOutputStream();
          InputStreamReader inr=new InputStreamReader(in);
          BufferedReader bfw=new BufferedReader(inr);
          String s=s=bfw.readLine();
          System.out.println(s);
    
    
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
     super.run();
          }}          
    
  • 客户端:

  • 创建Socket对象,并连接服务器
  • 调用getInputStream/getOutputStream方法,进行I/O
  • 关闭Socket

     public class ClientT {
         public static void main(String[] args) {
         System.out.println("客户端启动成功");
    try {
        Socket socket = new Socket("127.0.0.1", 888);
       OutputStream out = socket.getOutputStream();
    OutputStreamWriter outt=new OutputStreamWriter(out);    
    PrintWriter printWriter = new PrintWriter(outt);    
        String s = "客户端测试";
        printWriter.println(s);
        printWriter.flush();
        printWriter.close();
                    out.close();
        } catch (Exception e) {
         e.printStackTrace();
    }   
         }
           }
    

    `

    udp编程

    UDP数据报协议,是一个无连接,不可靠的协议。即:数据的发送方只负责将数据发送出去,数据的接受方只负责接受数据。发送方和接收方不会相互确认数据的传输是否成功。

    // 服务端
    public class Udpserver {
    public static void main(String[] args) {
    System.out.println("服务器启动");
          try {
        DatagramSocket ds=new DatagramSocket(8989);
       byte[] buf=new byte[1024];
           DatagramPacket p=new DatagramPacket(buf, buf.length);
         ds.receive(p);
          String str=new String(buf,0,p.getLength());
    System.out.println(str);
    ///////////////////////////////
    
    
    String s="你好,我是服务器";
    byte[] bf=s.getBytes();
    DatagramPacket p1=new DatagramPacket(bf, bf.length,p.getSocketAddress());
    ds.send(p1);    
           } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
                   }
                  }
                }
    
  • 接收端:DtagramPacket p=new DatagramPacket(bf, bf.length);

  • 发送端:DtagramPacket p=new DatagramPacket(bf, bf.length,SocketAddress());//后面要跟上地址。
  • soketAddress也可以写成 地址和端口。

         public class UdpClient {
           public static void main(String[] args) {
    try {
        DatagramSocket ds = new DatagramSocket();
        String s = "你好,我是客户端";
        byte[] buf = s.getBytes();// 吧字符串-》字节码
        // DatagramPacket dp = new DatagramPacket(buf, buf.length,
        // new InetSocketAddress("localhost", 8989));
        DatagramPacket dp = new DatagramPacket(buf, buf.length,
                InetAddress.getByName("localhost"), 8989);
        ds.send(dp);
        // //////////////////////
        byte[] buf2 = new byte[1024];
        DatagramPacket dp2 = new DatagramPacket(buf2, buf2.length);
        ds.receive(dp2);
        String sw = new String(buf2, 0, dp2.getLength());
        System.out.println(sw);
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    
    }
              }
    
    Url编程
    • 创建URL对象
    • 调用URL对象的openConnection方法,获得URLConnection
    • 调用URLConnection方法的getInputStream,获得输入流,从而读 取资源
    • I/O操作
    • 关闭I/O流

        URl url=new URL("http://baidu.com");
        URLConnection ucon=url.openConnection();
        InputStream in=ucaon.getInputStream();
        InputStreamReader rd=new                              InputStreamReader(in);
        BufferedReader brd=new                  BufferedReader(rd);
        String s;
        while((s=brd.readLine())!=null){
         System.out.println(s);
         brd.close();
             } 
      

kxind

性别:男. 敢于尝试 爱折腾的死宅程序猿. https://github.com/kxinds