java网络编程之TCP/IP ——SocketServer与Socket

java网络编程主要包含4部分: (注意设置超时时间) 
1.URL 连接  :类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询。 
2.HttpURLConnection连接:相当于servlet,发送单个以post或get方式的请求, 
3.TCP/IP连接   可靠传输ServerSocket类 
4.UDP连接      DatagramSocket 类,  此类表示用来发送和接收数据报包的套接字。 

TCP/IP 连接 Server服务器端 

Java代码  收藏代码
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedReader;  
  3. import java.io.BufferedWriter;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.io.OutputStreamWriter;  
  8. import java.net.ServerSocket;  
  9. import java.net.Socket;  
  10.   
  11.   
  12. /** 
  13.  *@ClassName:Server 
  14.  *@author: chenyoulong   
  15.  *@date :2012-7-30 上午10:35:09 
  16.  *@Description:TODO  
  17.  */  
  18. public class SendServer {  
  19.   
  20.     /** 
  21.      * @throws IOException   
  22.      * @Title: main  
  23.      * @Description: TODO  
  24.      * @param @param args    
  25.      * @return void    
  26.      * @throws  
  27.      */  
  28.     public static void main(String[] args) throws IOException {  
  29.         // TODO Auto-generated method stub  
  30.        ServerSocket server=new ServerSocket(8888);  
  31.        System.out.println("server start");  
  32.        Socket sock=server.accept();  
  33.        sock.setSoTimeout(6000);   //服务器端设置连接超时时间,该操作只对读取(read)操作有效。  
  34.   
  35.        //读取  
  36.        //字节流的形式读取     
  37.        // 优缺点分析,弱点:受byte[]大小的限制  ,优点:不受回车符(\r)和换行符(\n)限制  
  38.        InputStream input=sock.getInputStream();  
  39.        byte[] buf =new byte[1024];  
  40.        System.out.println("InputStream==="+input);  
  41.        if(input!=null){  
  42.            int len=input.read(buf);  
  43.            ToolKit.writeLog(SendServer.class.getName(), "服务器端收到的报文:\n"+new String(buf, 0, len));  
  44.        }  
  45.               
  46.          
  47.       /* //字符流的形式读取 
  48.           //(遇到换行符或者回车符就终止,还是谨慎使用) 
  49.        BufferedReader read=new BufferedReader(new InputStreamReader(sock.getInputStream())); 
  50.        String readStr=null; 
  51.        if((readStr=read.readLine())!=null){ 
  52.            ToolKit.writeLog(Server.class.getName(), "服务器端收到的报文:\n"+readStr); 
  53.        } 
  54.        if(read!=null) read.close(); 
  55.        */  
  56.          
  57.          
  58.        /*//输出 
  59.        String outStr="我是server服务器端"; 
  60.        BufferedWriter write=new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())); 
  61.        
  62.        if(outStr!=null){ 
  63.            write.write(outStr); 
  64.        } 
  65.        if(write!=null) write.close();*/  
  66.          
  67.          
  68.        //挂关闭资源  
  69.        if(sock!=null) sock.close();  
  70.        if(server!=null) server.close();  
  71.     }  



TCP/IP连接 Client客户端 

Java代码  收藏代码
    1. import java.io.BufferedInputStream;  
    2. import java.io.BufferedOutputStream;  
    3. import java.io.IOException;  
    4. import java.net.Socket;  
    5. import java.net.UnknownHostException;  
    6. import org.apache.log4j.Logger;  
    7.   
    8.   
    9. /** 
    10.  *@ClassName:ReceiveClient 
    11.  *@author: chenyoulong   
    12.  *@date :2012-8-3 下午2:17:26 
    13.  *@Description:TODO  
    14.  */  
    15. public class ReceiveClient {  
    16.     private final String IP=Setting.RECEIVE_IP;  
    17.     private final int PORT=Setting.RECEIVE_PORT;  
    18.     private  Logger log = Logger.getLogger(Sender.class.getName());  
    19.     //发送  
    20.     /** 
    21.      * @throws Exception  
    22.      * 发送报文 
    23.      * @Title: send  
    24.      * @Description: TODO  
    25.      * @param @param reqMessage    
    26.      * @return void    
    27.      * @throws 
    28.      */  
    29.    public void send(String reqMessage) throws Exception{  
    30.        Socket sock=null;  
    31.        BufferedOutputStream out=null;  
    32.        try {  
    33.         sock=new Socket();  
    34.   
    35.                   SocketAddress sockAdd=new InetSocketAddress(IP, PORT);  
    36.              sock.connect(sockAdd, 2000); //客户端设置连接建立超时时间  
    37.   
    38.              out=new BufferedOutputStream(sock.getOutputStream());  
    39.         out.write(reqMessage.getBytes());  
    40.         out.flush();  
    41.           
    42.     } catch (UnknownHostException e) {  
    43.         // TODO Auto-generated catch block  
    44.         log.error("网络连接异常"+Strings.getStackTrace(e));  
    45.         e.printStackTrace();  
    46.     } catch (IOException e) {  
    47.         // TODO Auto-generated catch block  
    48.         log.error("网络连接异常\n"+Strings.getStackTrace(e));  
    49.         e.printStackTrace();  
    50.     }finally{  
    51.         if(out!=null){  
    52.             try {  
    53.                 out.close();  
    54.             } catch (IOException e) {  
    55.                 // TODO Auto-generated catch block  
    56.                 e.printStackTrace();            }  
    57.         }  
    58.         if(sock!=null){  
    59.             try {  
    60.                 sock.close();  
    61.             } catch (IOException e) {  
    62.                 // TODO Auto-generated catch block  
    63.                     e.printStackTrace();  
    64.         }  
    65.         }  
    66.     }   
    67.    }  
    68.       
    69.       
    70.     //接收  
    71.     public String  reiceve() throws Exception{  
    72.         Socket sock=null;  
    73.         BufferedInputStream in=null;  
    74.             
    75.             try {  
    76.                 sock=new Socket(IP,PORT);  
    77.                 in = new BufferedInputStream(sock.getInputStream());  
    78.                  if ((sock == null) || (in == null)) {  
    79.                         throw new Exception("套接口无效,无法读取数据");  
    80.                   }  
    81.                   
    82.             } catch (UnknownHostException e) {  
    83.                 // TODO Auto-generated catch block  
    84.                 e.printStackTrace();  
    85.                   
    86.             } catch (IOException e) {  
    87.                 // TODO Auto-generated catch block  
    88.                 e.printStackTrace();  
    89.             }  
    90.               
    91.              byte[] bts = new byte[10000];  
    92.              int totalLen = 0, len = 0;  
    93.              while ((len = in.read(bts, totalLen, 1000)) != -1) {  
    94.                     totalLen += len;  
    95.                 }  
    96.              String result = new String(bts);  //注意字符编码  
    97.              return result.trim();  
    98.     }   
    99.       
    100.   
    101. //main函数示例  
    102.   
    103.     public static void main(String[] args){  
    104.         //发送报文  
    105.       
    106.           
    107.         //发送  
    108.                                String str="我是客户端!"        
    109.         try {  
    110.                 new ReceiveClient().send(str);  
    111.             } catch (Exception e) {  
    112.                 // TODO Auto-generated catch block  
    113.                 e.printStackTrace();  
    114.             }  
    115.           
    116.           
    117.         //接收报文  
    118.         /*try { 
    119.             String recStr=new Receiver().reiceve(); 
    120.             System.out.println("客户端接收到的结果=="+recStr); 
    121.                     } catch (Exception e) { 
    122.             // TODO Auto-generated catch block 
    123.             e.printStackTrace(); 
    124.         }*/  
    125.     }  
    126. }  
原文地址:https://www.cnblogs.com/suifengbingzhu/p/2649688.html