자기가 쓴 socket 통신 코드

4677 단어 Java
package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class socket {
    public static void main(String[] args) throws IOException, InterruptedException {
        //          TCP   
        Socket client = new Socket("0.0.0.0", 9900);
        client.setSoTimeout(7000);
        //  Socket    ,            
        PrintStream out = new PrintStream(client.getOutputStream());
        //  Socket    ,                 
        BufferedReader buf =  new BufferedReader(new InputStreamReader(client.getInputStream()));
        boolean flag = true;
        while(flag){
            //System.out.print("    :");
            //String str = input.readLine();
            String str = "00009b08d5ca3553d9172f464312b6db00140003";
            //        
            byte []buf1 = new byte[20];
            for(int i=0;i<20;i++){
            //      16    
                buf1[i] = (byte) Integer.parseInt(str.substring(i*2, i*2+2),16);
                //System.out.println(str.substring(i*2, i*2+2));
            }
            //System.out.println();
            try {
            //    
                out.write(buf1, 0, buf1.length);        
                System.out.println("  ");
            } catch (Exception e) {
                System.out.println("  ");
            }
            if("bye".equals(str)){
                flag = false;
                System.out.println("  ");
            }else{
//              try{
//                  //               (    ,       ),       ,       
//                  String echo = buf.readLine();
//                  System.out.println(echo);
//              }catch(SocketTimeoutException e){
//                  System.out.println("Time out, No response");
//              }
            }
            //  10       
            Thread.sleep(10000);
        }
        input.close();
        if(client != null){
            //            ,      ,         ,      
            client.close(); //   socket,              
        }
    }

}

좋은 웹페이지 즐겨찾기