中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

Java網(wǎng)絡(luò)編程入門(mén)SocketServer與Socket

2018-07-20    來(lái)源:open-open

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬(wàn)Linux鏡像隨意使用

java網(wǎng)絡(luò)編程主要包含4部分: (注意設(shè)置超時(shí)時(shí)間)

  1. URL 連接 :類URL代表一個(gè)統(tǒng)一資源定位符,它是指向互聯(lián)網(wǎng)“資源”的指針。資源可以是簡(jiǎn)單的文件或目錄,也可以是對(duì)更為復(fù)雜的對(duì)象的引用,例如對(duì)數(shù)據(jù)庫(kù)或搜索引擎的查詢。
  2. HttpURLConnection連接:相當(dāng)于servlet,發(fā)送單個(gè)以post或get方式的請(qǐng)求,
  3. TCP/IP連接 可靠傳輸ServerSocket類 。 1).入門(mén)案例。 2).多線程阻塞式通訊。 阻塞式:比如recv某個(gè)socket的描述符,如果沒(méi)有數(shù)據(jù)到,一直停在recv的狀態(tài),不釋放socket資源,叫阻塞
  4. UDP連接 DatagramSocket 類, 此類表示用來(lái)發(fā)送和接收數(shù)據(jù)報(bào)包的套接字。

TCP/IP 連接 Server服務(wù)器端

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *@ClassName:Server
 *@author: chenyoulong  
 *@date :2012-7-30 上午10:35:09
 *@Description:TODO 
 */
public class SendServer {

    /**
     * @throws IOException  
     * @Title: main 
     * @Description: TODO 
     * @param @param args   
     * @return void   
     * @throws 
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
       ServerSocket server=new ServerSocket(8888);
       System.out.println("server start");
       Socket sock=server.accept();
       sock.setSoTimeout(6000);   //服務(wù)器端設(shè)置連接超時(shí)時(shí)間,該操作只對(duì)讀取(read)操作有效。

       //讀取
       //字節(jié)流的形式讀取   
       // 優(yōu)缺點(diǎn)分析,弱點(diǎn):受byte[]大小的限制  ,優(yōu)點(diǎn):不受回車(chē)符(\r)和換行符(\n)限制
       InputStream input=sock.getInputStream();
       byte[] buf =new byte[1024];
       System.out.println("InputStream==="+input);
       if(input!=null){
           int len=input.read(buf);
           ToolKit.writeLog(SendServer.class.getName(), "服務(wù)器端收到的報(bào)文:\n"+new String(buf, 0, len));
       }

      /* //字符流的形式讀取
          //(遇到換行符或者回車(chē)符就終止,還是謹(jǐn)慎使用)
       BufferedReader read=new BufferedReader(new InputStreamReader(sock.getInputStream()));
       String readStr=null;
       if((readStr=read.readLine())!=null){
           ToolKit.writeLog(Server.class.getName(), "服務(wù)器端收到的報(bào)文:\n"+readStr);
       }
       if(read!=null) read.close();
       */

       /*//輸出
       String outStr="我是server服務(wù)器端";
       BufferedWriter write=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));

       if(outStr!=null){
           write.write(outStr);
       }
       if(write!=null) write.close();*/

       //掛關(guān)閉資源
       if(sock!=null) sock.close();
       if(server!=null) server.close();
    }

TCP/IP連接 Client客戶端

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;

/**
 *@ClassName:ReceiveClient
 *@author: chenyoulong  
 *@date :2012-8-3 下午2:17:26
 *@Description:TODO 
 */
public class ReceiveClient {
    private final String IP=Setting.RECEIVE_IP;
    private final int PORT=Setting.RECEIVE_PORT;
    private  Logger log = Logger.getLogger(Sender.class.getName());
    //發(fā)送
    /**
     * @throws Exception 
     * 發(fā)送報(bào)文
     * @Title: send 
     * @Description: TODO 
     * @param @param reqMessage   
     * @return void   
     * @throws
     */
   public void send(String reqMessage) throws Exception{
       Socket sock=null;
       BufferedOutputStream out=null;
       try {
        sock=new Socket();

                  SocketAddress sockAdd=new InetSocketAddress(IP, PORT);
             sock.connect(sockAdd, 2000); //客戶端設(shè)置連接建立超時(shí)時(shí)間

             out=new BufferedOutputStream(sock.getOutputStream());
        out.write(reqMessage.getBytes());
        out.flush();

    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        log.error("網(wǎng)絡(luò)連接異常"+Strings.getStackTrace(e));
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error("網(wǎng)絡(luò)連接異常\n"+Strings.getStackTrace(e));
        e.printStackTrace();
    }finally{
        if(out!=null){
            try {
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();            }
        }
        if(sock!=null){
            try {
                sock.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
        }
        }
    } 
   }

    //接收
    public String  reiceve() throws Exception{
        Socket sock=null;
        BufferedInputStream in=null;

            try {
                sock=new Socket(IP,PORT);
                in = new BufferedInputStream(sock.getInputStream());
                 if ((sock == null) || (in == null)) {
                        throw new Exception("套接口無(wú)效,無(wú)法讀取數(shù)據(jù)");
                  }

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             byte[] bts = new byte[10000];
             int totalLen = 0, len = 0;
             while ((len = in.read(bts, totalLen, 1000)) != -1) {
                    totalLen += len;
                }
             String result = new String(bts);  //注意字符編碼
             return result.trim();
    } 

//main函數(shù)示例

    public static void main(String[] args){
        //發(fā)送報(bào)文

        //發(fā)送
                               String str="我是客戶端!"      
        try {
                new ReceiveClient().send(str);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        //接收?qǐng)?bào)文
        /*try {
            String recStr=new Receiver().reiceve();
            System.out.println("客戶端接收到的結(jié)果=="+recStr);
                    } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
    }
}

TCP/IP連接多線程阻塞式服務(wù)端1——實(shí)現(xiàn)runnable接口

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 *@ClassName:ThreadSocket
 *@author: chenyoulong  
 *@date :2012-8-1 上午10:00:41
 *@Description:TODO 
 */
public class ThreadSocket implements Runnable {
    private Socket sock;
    public ThreadSocket(Socket sock){
        this.sock=sock;
    }

    /* 
     * <p>Title: run</p> 
     * <p>Description: </p>  
     * @see java.lang.Runnable#run() 
     */
    public void run() {
        // TODO Auto-generated method stub
        InputStream input=null;
        try {
            input = sock.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        /*  //字符流的形式讀取(遇到換行符或者回車(chē)符就終止,還是謹(jǐn)慎使用)
           BufferedReader read=new BufferedReader(new InputStreamReader(input));
           String readStr=null;
           try {
            if((readStr=read.readLine())!=null){
                   System.out.println("服務(wù)器端收到的報(bào)文:\n"+readStr);
               }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

           if(read!=null) {
               try {
                read.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           }*/

        //字節(jié)流
        byte[] buf = new byte[1024];        
        if (input != null) {
            int len=0;
            try {
                len = input.read(buf);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("服務(wù)器端收到的報(bào)文:\n"+ new String(buf, 0, len));
        }
    }

}

TCP/IP連接多線程阻塞式服務(wù)端2——main函數(shù)

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *@ClassName:OnRunSendServer
 *@author: chenyoulong  
 *@date :2012-8-1 上午10:06:28
 *@Description:TODO 
 */
public class OnRunSendServer {

    /**
     * @throws IOException  
     * @Title: main 
     * @Description: TODO 
     * @param @param args   
     * @return void   
     * @throws 
     */
    public static void main(String[] args)  {
        // TODO Auto-generated method stub
        ServerSocket server = null;
        try {
            server = new ServerSocket(8888);
            System.out.println("send服務(wù)器start!");
            Socket sock = null;
            while (true) {
                sock = server.accept();
                sock.setSoTimeout(12000);//設(shè)置讀取連接超時(shí)時(shí)間
                ThreadSocket tsock = new ThreadSocket(sock);
                new Thread(tsock).start();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }/*finally{  //這里還是不要finally關(guān)閉ServerSocket為好,防止某個(gè)socket連接超時(shí)導(dǎo)致整個(gè)ServerSocket都關(guān)閉了。
            try {
                server.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }*/
    }

}

標(biāo)簽: 服務(wù)器 服務(wù)器端 互聯(lián)網(wǎng) 數(shù)據(jù)庫(kù) 搜索 搜索引擎 網(wǎng)絡(luò)

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:java桶式排序算法

下一篇:java 強(qiáng)制中斷線程運(yùn)行