兩個(gè)程序間通信(一):Java Socket

File server and client

GENERAL USAGE
—————————————

  • Start server.java first by typing “java server” in a terminal window.

  • Start the client.java by typing “java client ‘host-name’ ‘file-name’” in a terminal
    window where host-name is the host to use and file-name is the required file.

  • 這個(gè)是單線程處理,接受連接請(qǐng)求和處理連接是基本的業(yè)務(wù)邏輯。

  • 多線程和線程池的解決方案

Server:

//*****************************************************************
// server.java 
//
// Allows clients to connect and request files.  If the file
// exists it sends the file to the client.  
//*****************************************************************

import java.lang.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class server 
{
    private final static int PORT = 12345;
    private final static int QUEUE_SIZE = 10;
    private final static int BUF_SIZE = 4096;
    
    public static void main(String[] args)
    {
        try {
            // Create the server socket
            ServerSocket sSocket = new ServerSocket(PORT, QUEUE_SIZE);
            
            // Socket is set up and will wait for connections
            while (true) {  //不用true會(huì)好一些
                // Listen for a connection to be made to this socket and accept it
                Socket cSocket = sSocket.accept();
                byte[] byteArray = new byte[BUF_SIZE];
                
                // Get the name of the file from the client
                Scanner scn = new Scanner(cSocket.getInputStream());
                String fileName = scn.next();
                
                // Send the contents of the file
                BufferedInputStream bis = new 
            BufferedInputStream(new FileInputStream(fileName));
                OutputStream outStream = cSocket.getOutputStream();
                while(bis.available() > 0) {
                    bis.read(byteArray, 0, byteArray.length);
                    outStream.write(byteArray, 0, byteArray.length);
                }
                            
                // Close
                bis.close();
                cSocket.close();
            }
        }
        catch(EOFException eofe) {
            eofe.printStackTrace();
            System.exit(1);
        }
        catch(FileNotFoundException fnfe) {
            fnfe.printStackTrace();
            System.exit(1);
        }
        catch(IllegalArgumentException iae) {
            iae.printStackTrace();
            System.out.println("Bind failed");
            System.exit(1);
        }
        catch(IOException ioe) {
            ioe.printStackTrace();
            System.out.println("Could not complete request");
            System.exit(1);
        }   
    }
}

Client:

//*****************************************************************
// client.java 
//
// Connects to the server and sends a request for a file by 
// the file name.  Prints the file contents to standard output.  
//*****************************************************************

import java.lang.*;
import java.io.*;
import java.net.*;

public class client 
{
    private final static int PORT = 12345;
    private final static int BUF_SIZE = 4096;
    
    public static void main(String[] args)
    {       
        // Set up socket using host name and port number
        try {
            // Get host name and file name from command line arguments
            String host = args[0];
            String fileName = args[1];
            
            Socket s = new Socket(host, PORT);
            byte[] byteArray = new byte[BUF_SIZE];
            // Send filename to the server
            PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
            pw.println (fileName);
            
            // Get the file from the server and print to command line
            DataInputStream fromServer = new DataInputStream(s.getInputStream());
            
            while(fromServer.read(byteArray) > 0) {
                System.out.println(new String(byteArray, "UTF-8"));
            }
            
            fromServer.close();
            s.close();
        }
        catch(IndexOutOfBoundsException iobe) {
            System.out.println("Usage: client host-name file-name");
            System.exit(1);
        }
        catch(UnknownHostException unhe) {
            unhe.printStackTrace();
            System.out.println("Unknown Host, Socket");
            System.exit(1);
        }
        catch(IOException ioe) {
            ioe.printStackTrace();
            System.exit(1);
        }
    }
}

注意:

Server進(jìn)入Socket cSocket = sSocket.accept();的時(shí)候,判斷語句內(nèi)容其實(shí)不是很重要,有的地方寫成 if ( !serverSocket.close( )){ 假設(shè)我們一定要進(jìn)入accept(),那含義是一樣的。ServerSocket的accept()本身是個(gè)當(dāng)前線程阻塞方法(一個(gè)線程在執(zhí)行過程中暫停,以等待某個(gè)條件的觸發(fā),或者說是等待所有資源到位),那么,當(dāng)它只有接受一個(gè)客戶端的鏈接時(shí),才會(huì)往下執(zhí)行,在此之前將一直等待,無限原地循環(huán),如果直接關(guān)閉ServerSocket,那么會(huì)報(bào)socket異常,因?yàn)椋?/p>

public Socket accept() throws IOException {  
       if (isClosed())  
           throw new SocketException("Socket is closed");    //here
       if (!isBound())  
           throw new SocketException("Socket is not bound yet");  
       Socket s = new Socket((SocketImpl) null);  
       implAccept(s);  
       return s;  
   } 

解決方案,可以創(chuàng)建一個(gè)新的socket鏈接,并且改變flag值:

public void stopThread(){  
        this.flag = false;  
        try {  
            new Socket("localhost",50001);  
        } catch (UnknownHostException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  

網(wǎng)上看到的另外一個(gè)版本:
Server:

package socket;
 
import java.io.*;
import java.net.*;
 
public class TcpServer {
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(9091);
        try {
            Socket client = server.accept();
            try {
                BufferedReader input =
       new BufferedReader(new InputStreamReader(client.getInputStream()));
                boolean flag = true;
                int count = 1;
 
                while (flag) {
                    System.out.println(客戶端要開始說話了,這是第 + count + 次!);
                    count++;
                     
                    String line = input.readLine();
                    System.out.println(客戶端說: + line);
                     
                    if (line.equals(exit)) {
                        flag = false;
                        System.out.println(客戶端不想玩了!);
                    } else {
                        System.out.println(客戶端說:  + line);
                    }
 
                }
            } finally {
                client.close();
            }
             
        } finally {
            server.close();
        }
    }
}

Client:

package socket;
 
import java.io.*;
import java.net.*;
import java.util.Scanner;
 
public class TcpClient {
    public static void main(String[] args) throws Exception {
        Socket client = new Socket(127.0.0.1, 9091);
        try {
            PrintWriter output =
                    new PrintWriter(client.getOutputStream(), true);
            Scanner cin = new Scanner(System.in);
            String words;
 
            while (cin.hasNext()) {
                words = cin.nextLine();
 
                output.println(words);
 
                System.out.println(寫出了數(shù)據(jù):  + words);
            }
 
            cin.close();
        } finally {
            client.close();
        }
    }
}

這是一個(gè)socket套接字通信的圖:


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,992評(píng)論 19 139
  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光劍書架上的書閱讀 3,948評(píng)論 2 8
  • 海 2016-03-30 海最深的地方是什么。 城市的北邊是海,在很北的地方。其實(shí)也看不到海,是一片黑色的淤泥,有...
    dddddVincent閱讀 156評(píng)論 0 0
  • 今天,我們來說一說精力管理。 似乎說到精力管理這個(gè)詞,就免不了想到時(shí)間管理,有節(jié)制的人生、自律而規(guī)律的生活,以及或...
    睡午覺的貓兒閱讀 1,931評(píng)論 4 20
  • 坐禪十年,還是七情六欲 閉關(guān)一生,還是心如苦膽 遁入空門,還是苦海無邊 看破紅塵,還是悲從中來 陋室之居,還是憂心...
    沒有鑰匙開過那把鎖閱讀 119評(píng)論 0 1