आपके पास क्लाइंट के लिए जाने वाले पोर्ट पर केवल एक 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 है।
हां यह है। एक सर्वर सॉकेट, लेकिन ग्राहकों को संभालने के लिए एकाधिक सॉकेट और थ्रेड। – Thihara
असंबद्ध धागे निर्माण से सावधान रहें! आप धागे की कुल संख्या को बेहतर सीमित कर चुके थे। आपकी सबसे अच्छी शर्त यहां 'निष्पादक सेवा' का उपयोग करना है। – fge
क्या मुझे सिर्फ एक सॉकेट बनाना चाहिए जो कनेक्शन को संभालता है और फिर उपयोगकर्ता को एक अद्वितीय सॉकेट पर निर्देशित करता है? – user2016705