2013-06-20 60 views
5

我一直在學習有關套接字的一段時間(我很年輕),我認爲我對Java套接字有很好的掌握。我決定創建一個簡單的多人Java 2D社交遊戲。我的目標是讓服務器輸出玩家的X,Y座標並每10毫秒進行一次聊天。從我讀過的內容來看,我的平均邏輯告訴我,一次只有一個用戶可以連接到一個套接字。因此,我需要爲每個連接的播放器分別設置一個線程和套接字。我需要一個單獨的套接字和線程來連接每個玩家嗎? [JAVA]

是否需要每個玩家有一個ServerSocket和線程?

+1

是的。一個ServerSocket,但多個套接字和線程來處理客戶端。 – Thihara

+2

請注意無限的線程創建!你最好限制線程的總數。你最好的選擇是在這裏使用'ExecutorService'。 – fge

+1

我應該創建一個處理連接的套接字,然後將用戶指向一個唯一的套接字? – user2016705

回答

6

您應該只有一個ServerSocket監聽客戶端已知的端口。當客戶端連接到服務器時,會創建一個新的Socket對象,並且原始的ServerSocket會再次返回到偵聽。然後你應該創建一個新的Thread或交給Executor與客戶交談的實際工作,否則你的服務器將停止監聽客戶端連接。

這是一個你將需要的代碼的基本草圖。

import java.net.*; 
import java.util.concurrent.*; 

public class CoordinateServer { 
    public static void main(String... argv) throws Exception { 
    // 'port' is known to the server and the client 
    int port = Integer.valueOf(argv[0]); 
    ServerSocket ss = new ServerSocket(port); 

    // You should decide what the best type of service is here 
    ExecutorService es = Executors.newCachedThreadPool(); 

    // How will you decide to shut the server down? 
    while (true) { 
     // Blocks until a client connects, returns the new socket 
     // to use to talk to the client 
     Socket s = ss.accept(); 

     // CoordinateOutputter is a class that implements Runnable 
     // and sends co-ordinates to a given socket; it's also 
     // responsible for cleaning up the socket and any other 
     // resources when the client leaves 
     es.submit(new CoordinateOutputter(s)); 
    } 
    } 
} 

我已經把這裏的插座,因爲他們更容易上手,但一旦你有這方面的工作,並且希望提高你的表現,你可能會想調查java.nio.channels包。有一個很好的教程over at IBM

+0

感謝您的回答 – user2016705

3

是的。

Socket是兩點(客戶端和服務器)之間的連接。這意味着每個玩家都需要在服務器端使用自己的套接字連接。

如果您希望您的應用程序以任何有意義的方式進行響應,那麼服務器上的每個傳入連接都應在其自己的線程內處理。

這樣可以讓連接速度慢的客戶端不會成爲別人的瓶頸。這也意味着,如果客戶端連接丟失,則不會加重等待超時的更新。

+0

謝謝您的回答 – user2016705