java-socket編程,javasocket

來源:互聯網
上載者:User

java-socket編程,javasocket

先前有篇博文專門寫了socket的基本概念,這裡用java來實現簡單的server-client的socket資料轉送。

server端

/** * socket服務端 *  * @author peter_wang * @create-time 2014-8-30 下午3:25:27 */public class Server {    public static void main(String args[])        throws IOException {        int port = 8888;        ServerSocket server = new ServerSocket(port);        while (true) {            // 開始接受socket請求            Socket socket = server.accept();            // 建立新線程處理新進的socket請求            new Thread(new Task(socket)).start();        }    }    /**     * 處理Socket請求的非同步任務     */    static class Task        implements Runnable {        private Socket mSocket;        public Task(Socket socket) {            this.mSocket = socket;        }        public void run() {            try {                handleSocket();            }            catch (Exception e) {                e.printStackTrace();            }        }        /**         * 跟用戶端Socket進行通訊         *          * @throws Exception         */        private void handleSocket()            throws Exception {            BufferedReader br = new BufferedReader(new InputStreamReader(mSocket.getInputStream(), "UTF-8"));            StringBuilder sb = new StringBuilder();            String temp;            int index;            while ((temp = br.readLine()) != null) {                // 遇到eof時結束接收                if ((index = temp.indexOf("eof")) != -1) {                    System.out.println(temp);                    sb.append(temp.substring(0, index));                    break;                }                sb.append(temp);            }            System.out.println("data from client: " + sb);            // 寫操作            Writer writer = new OutputStreamWriter(mSocket.getOutputStream());            writer.write("Hello Client.");            writer.write("eof\n");            writer.flush();            writer.close();            br.close();            mSocket.close();        }    }}

client端

/** * socket用戶端 *  * @author peter_wang * @create-time 2014-8-30 下午4:13:11 */public class Client {    public static void main(String args[])        throws Exception {        String host = "127.0.0.1"; // 本地地址        int port = 8888;        // 與服務端建立串連        Socket client = new Socket(host, port);        Scanner sc = new Scanner(System.in);        String str = sc.nextLine();        System.out.println("輸入的內容為:" + str);        // 建立串連後就可以往服務端寫資料了        Writer writer = new OutputStreamWriter(client.getOutputStream(), "UTF-8");        writer.write(str);        writer.write("eof\n");        writer.flush();        // 寫完以後進行讀操作        BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));        StringBuffer sb = new StringBuffer();        String temp;        int index;        while ((temp = br.readLine()) != null) {            if ((index = temp.indexOf("eof")) != -1) {                sb.append(temp.substring(0, index));                break;            }            sb.append(temp);        }        System.out.println("from server: " + sb);        writer.close();        br.close();        client.close();    }}

1.用了eof做完讀寫結束標識。

2.BufferedReader提高了IO效率,用非同步提前準備好資料存放區到記憶體,讀取直接從記憶體讀,如果資料來源於磁碟IO或網路IO,速度將快很多,磁碟讀取和記憶體讀取的速度對比參見這篇文章。

3.server和client之間資料轉送需要統一編碼,防止亂碼。

4.源碼分析,server端的new ServerSocket(port)實現了new socket、bind、listener功能

public void bind(SocketAddress endpoint, int backlog) throws IOException {if (isClosed())    throw new SocketException("Socket is closed");if (!oldImpl && isBound())    throw new SocketException("Already bound");if (endpoint == null)    endpoint = new InetSocketAddress(0);if (!(endpoint instanceof InetSocketAddress))    throw new IllegalArgumentException("Unsupported address type");InetSocketAddress epoint = (InetSocketAddress) endpoint;if (epoint.isUnresolved())    throw new SocketException("Unresolved address");if (backlog < 1)  backlog = 50;try {    SecurityManager security = System.getSecurityManager();    if (security != null)security.checkListen(epoint.getPort());    getImpl().bind(epoint.getAddress(), epoint.getPort());    getImpl().listen(backlog);    bound = true;} catch(SecurityException e) {    bound = false;    throw e;} catch(IOException e) {    bound = false;    throw e;}    }
client端的new Socket(host, port)實現了new socket和connect功能

private Socket(SocketAddress address, SocketAddress localAddr,   boolean stream) throws IOException {setImpl();// backward compatibilityif (address == null)    throw new NullPointerException();try {    createImpl(stream);    if (localAddr != null)bind(localAddr);    if (address != null)connect(address);} catch (IOException e) {    close();    throw e;}    }




JAVA socket編程

這是應為你程式運行後沒有關閉連接埠就一直佔用,所以會拋連接埠佔用異常
 
java socket編程 用在什地方 為何要用?

進程通訊用,建議百度百科

簡單的Client/Server程式
1.用戶端程式
import java.io.*;import java.net.*;public class TalkClient { public static void main(String args[]) { try { Socket socket = new Socket("127.0.0.1", 4700); //向原生4700連接埠發出客戶請求 BufferedReader sin = new BufferedReader(new InputStreamReader(System.in)); //由系統標準輸入裝置構造BufferedReader對象 PrintWriter os = new PrintWriter(socket.getOutputStream()); //由Socket對象得到輸出資料流,並構造PrintWriter對象 BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); //由Socket對象得到輸入資料流,並構造相應的BufferedReader對象 String readline; readline = sin.readLine(); //從系統標準輸入讀入一字串 while (!readline.equals("bye")) { //若從標準輸入讀入的字串為 "bye"則停止迴圈 os.println(readline); //將從系統標準輸入讀入的字串輸出到Server os.flush(); //重新整理輸出資料流,使Server馬上收到該字串 System.out.println("Client:" + readline); //在系統標準輸出上列印讀入的字串 System.out.println("Server:" + is.readLine()); //從Server讀入一字串,並列印到標準輸出上 readline = sin.readLine(); //從系統標準輸入讀入一字串 } //繼續迴圈 os.close(); //關閉Socket輸出資料流 is.close(); //關閉Socket輸入資料流 socket.close(); /&#4......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.