程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 簡略的java socket客戶端和辦事端示例

簡略的java socket客戶端和辦事端示例

編輯:關於JAVA

簡略的java socket客戶端和辦事端示例。本站提示廣大學習愛好者:(簡略的java socket客戶端和辦事端示例)文章只能為提供參考,不一定能成為您想要的結果。以下是簡略的java socket客戶端和辦事端示例正文


客戶端

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MyClient { 
    public static void main(String[] args) throws Exception { 
        Socket socket = new Socket("localhost", 10000); 
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
        PrintWriter out = new PrintWriter(socket.getOutputStream()); 
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 

        while (true) { 
            String msg = reader.readLine(); 
            out.println(msg); 
            out.flush(); 
            if (msg.equals("bye")) { 
                break; 
            } 
            System.out.println(in.readLine()); 
        } 
        socket.close(); 
    } 

辦事端

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer { 
    public static void main(String[] args) throws IOException { 
        ServerSocket server = new ServerSocket(10000); 

        while (true) { 
            Socket socket = server.accept(); 
            invoke(socket); 
        } 
    } 

    private static void invoke(final Socket client) throws IOException { 
        new Thread(new Runnable() { 
            public void run() { 
                BufferedReader in = null; 
                PrintWriter out = null; 
                try { 
                    in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
                    out = new PrintWriter(client.getOutputStream()); 

                    while (true) { 
                        String msg = in.readLine(); 
                        System.out.println(msg); 
                        out.println("Server received " + msg); 
                        out.flush(); 
                        if (msg.equals("bye")) { 
                            break; 
                        } 
                    } 
                } catch(IOException ex) { 
                    ex.printStackTrace(); 
                } finally { 
                    try { 
                        in.close(); 
                    } catch (Exception e) {} 
                    try { 
                        out.close(); 
                    } catch (Exception e) {} 
                    try { 
                        client.close(); 
                    } catch (Exception e) {} 
                } 
            } 
        }).start(); 
    } 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved