我想在java上使用套接字打开两个端口连接,但它不会工作。我在这里读到我应该使用SocketChannel而不是socket,但我想使用getInput / outputStream()方法,这对于Socket通道来说是不可能的。我想到了这样的事情:
public class ServeurMaitre {
public ServerSocket serverSocket = null;
int poolSize = 15;
Selector selector = null;
private ExecutorService pool = null;
boolean logged=false;
ServeurMaitre(int port1, int port2, int size){
try {
serverSocket = new ServerSocket(port1, size);
serverSocket = new ServerSocket(port2, size);
pool = Executors.newFixedThreadPool(poolSize);
System.out.println("Serveur en marche. En attente des clients");
} catch (IOException ex) {
Logger.getLogger(ServeurMaitre.class.getName()).log(Level.SEVERE, null, ex);
}
}
void ConnexionServeur() throws IOException {
while(true) {
Socket cnx = serverSocket.accept();
if (cnx.getLocalPort()==3333) {
pool.execute(new EsclaveXML(cnx, this));
}
if(cnx.getLocalPort()==8000) {
pool.execute(new EsclaveHTTP(cnx, this));
}
}
}
}
这个主要的:
public class Main{
public static void main(String[] args) throws IOException {
ServeurMaitre serveur = new ServeurMaitre(8000, 3333, 1);
serveur.Initialisation();
serveur.ConnexionServeur();
}
}
这是两个奴隶正在做的事情:
public class EsclaveHTTP implements Runnable{
Socket socket = null;
ServeurMaitre sm = null;
public EsclaveHTTP(Socket cnx, ServeurMaitre serveurMaitre) {
this.socket=cnx;
this.sm=serveurMaitre;
}
@Override
public void run() {
BufferedReader in = null;
PrintWriter out = null;
String message_distant = "";
try {
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
message_distant = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(message_distant); //etc etc and at the end:
if(!socket.isClosed())
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
和第二个
public class EsclaveXML implements Runnable{
Socket socket = null;
public EsclaveXML(Socket cnx, ServeurMaitre serveurMaitre) {
this.socket=cnx;
}
@Override
public void run() {
try {
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream(), "8859_1"), 1024);
StringBuffer sb = new StringBuffer();
InputStream ch = socket.getInputStream();
//System.out.println(ch);
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(ch, new ParseurXML());
}catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
catch(IOException e) {System.out.println(e);}
finally {
try { if(socket != null) socket.close();}
catch(IOException e) {}
}
}
}
但它只接受一个联系。
我怎么能做某种并行连接?
答案 0 :(得分:2)
您正在覆盖serverSocket变量
serverSocket = new ServerSocket(port1, size);
serverSocket = new ServerSocket(port2, size);
因此您只接受第二个连接。您需要两个变量,serverSocket1和serverSocket2,并在两者上调用accept()。