簡體   English   中英

實時應用程序(服務器/客戶端)的設計(類、方法、接口)

[英]Design(Classes, methods, interfaces) of real time applications(server/client)

我一直在尋找關於這個主題的好書或文章,但沒有找到太多。 對於特定場景,我沒有找到一個很好的例子——一段代碼。 就像客戶端/服務器對話一樣。 在我的應用程序協議中,他們必須發送/接收消息。 喜歡:服務器想要向客戶端發送文件客戶端可以接受或不接受,如果他接受,服務器將通過相同的連接/套接字發送字節。 我的應用程序的rest都使用阻塞方法,服務器有方法

這是我所做的:

服務器方式:

public synchronized void sendFile(File file)
{
  //send messsage asking if I can send a file
  //block on read, waiting for client responde
  //if client answers yes, start sending the bytes
  //else return
}

客戶端方法:

public void reciveCommand()
{
   //read/listen for a command from socket
   //if is a send file command handleSendFileCommand();
   //after the return of handleSendFileCommand() listen for another command
}

public void handleSendFileCommand()
{
   //get the file server want to send
   //check if it already has the file
   //if it already has, then send a command to the socket saying it already has and return         
   //else send a command saying server can send the file
   //create a FileInputStream, recive bytes and then return method
}

我 100% 確定這是錯誤的,因為服務器和客戶端不可能雙向對話,我的意思是,當服務器想要向服務器發送命令時,他們必須遵循命令的順序,直到對話結束,只有然后,他們可以發送/接收另一個命令序列。 這就是為什么我使所有發送請求的方法同步

我並沒有花很多時間意識到我需要研究那種應用程序的設計模式......我讀到了責任鏈設計模式,但我不明白如何使用它或其他好的設計模式情況。

我希望有人可以幫助我一些代碼示例。 提前致謝

Java 中的synchronized關鍵字意味着完全不同的東西——它將方法或代碼塊標記為一次只能執行單個線程的關鍵部分 你在這里不需要它。

然后,TCP 連接在字節流級別上雙向的。 服務器和客戶端之間的同步由交換的消息驅動。 將客戶端(幾乎同樣適用於服務器)想象為state machine 某些類型的消息在當前 state 中是可以接受的,有些不是,有些將節點切換到不同的 state。

由於您正在研究設計模式,因此State pattern在這里非常適用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM