1. 程式人生 > >簡單的通訊(二)----使用Socket實現TCP協議

簡單的通訊(二)----使用Socket實現TCP協議

客戶端向伺服器端傳送訊息,伺服器端給客戶端反饋訊息。程式碼和上一篇的程式碼差不多。

Client端程式碼

package com.demo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 
 * @author Lynn
 *  使用Socket類實現TCP協議; Socket常用的構造方法:Socket(InetAddress address, int
 *  port)和 Socket(String host, int port) 客戶端給服務端傳送資訊,服務端輸出此資訊到控制檯上;
 *
 */
public class Demo02 {
    // 客戶端;
    
    public static void main(String[] args) {
        InetAddress inet;
        Socket socket = null;
        OutputStream out = null;
        InputStream in = null;
        try {
            inet = InetAddress.getLocalHost();
            //這裡填寫伺服器端的ip和埠號;
            socket = new Socket(inet, 6868);
            out = socket.getOutputStream();
            out.write("我是客戶端".getBytes());
            //必須要主動關閉,否則無法收到伺服器端的回覆。這裡告訴伺服器端資料已經發送完了,這裡其實就是客戶端單方面關閉了輸出流,告訴伺服器端這次要傳送的訊息已經發送完畢,具體可以看附;
            socket.shutdownOutput();
            
            in = socket.getInputStream();
            int len;
            byte[] content = new byte[20];
            while((len=in.read(content))!=-1) {
                String str = new String(content,0,len);
                System.out.println("客戶端收到伺服器的回覆:"+str);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(out!=null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    
}

Server端程式碼

package com.demo;

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

public class Demo03 {
    // 伺服器端;
    public static void main(String[] args){
            //埠號;
            ServerSocket serverSocket=null;
            Socket socket =null;
            InputStream in = null;
            OutputStream out = null;
            try {
                serverSocket = new ServerSocket(6868);
                socket = serverSocket.accept();
                in = socket.getInputStream();
                byte[] content = new byte[20];
                int length;//記錄真正資料的長度;
                while ((length = in.read(content)) != -1) {
                    String str = new String(content, 0, length);
                    System.out.println("伺服器端收到客戶端的請求:"+str);
                } 
                out = socket.getOutputStream();
                out.write("我收到了你的訊息".getBytes());
                            //這裡不需要shutdownOutput程式可以正常結束,猜測是因為最後會執行out.close(),導致Socket關閉,客戶端可以自行結束。
                            //out.shutdownOutput();
                
            } catch (Exception e) {
                // TODO: handle exception
            }finally {
                if(out!=null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(in!=null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(socket!=null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if(serverSocket!=null) {
                    try {
                        serverSocket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            
        }

}

執行結果


關於socket中的shutdownOutput()shutdownIntput()方法分析https://blog.csdn.net/zhuoni2013/article/details/56494681