Combinez deux serveurs à un seul? – socket Java

J’ai donc essayé de créer un programme. Le programme est assez simple. Je veux faire un programme de chat avec l’envoi d’une photo. Le problème est maintenant que j’ai maintenant deux serveurs avec deux clients. Un pour le chat et un pour la photo. et je veux les combiner à un serveur pour rendre le code de plus en plus utile, mais je ne sais pas si c’est possible. Sinon, j’ai besoin d’une astuce pour continuer avec ça car maintenant je suis coincé. Donc, mon serveur ressemble à ceci. C’est possible?

Discussion de serveur:

public Server(int port) { this(port, null); } public Server(int port, ServerGUI sg) { // GUI or not this.sg = sg; // the port this.port = port; // to display hh:mm:ss sdf = new SimpleDateFormat("HH:mm:ss"); // ArrayList for the Client list al = new ArrayList(); } public void start() { keepGoing = true; /* create socket server and wait for connection requests */ try { // the socket used by the server ServerSocket serverSocket = new ServerSocket(port); // infinite loop to wait for connections while(keepGoing) { // format message saying we are waiting display("Server waiting for Clients on port " + port + "."); Socket socket = serverSocket.accept(); // accept connection // if I was asked to stop if(!keepGoing) break; ClientThread t = new ClientThread(socket); // make a thread of it al.add(t); // save it in the ArrayList t.start(); } // I was asked to stop try { serverSocket.close(); for(int i = 0; i < al.size(); ++i) { ClientThread tc = al.get(i); try { tc.sInput.close(); tc.sOutput.close(); tc.socket.close(); } catch(IOException ioE) { // not much I can do } } } catch(Exception e) { display("Exception closing the server and clients: " + e); } } // something went bad catch (IOException e) { String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n"; display(msg); } } class ClientThread extends Thread { // the socket where to listen/talk Socket socket; ObjectInputStream sInput; ObjectOutputStream sOutput; // my unique id (easier for deconnection) int id; // the Username of the Client String username; // the only type of message a will receive Message cm; // the date I connect String date; // Constructore ClientThread(Socket socket) { // a unique id id = ++uniqueId; this.socket = socket; /* Creating both Data Stream */ System.out.println("Thread trying to create Object Input/Output Streams"); try { // create output first sOutput = new ObjectOutputStream(socket.getOutputStream()); sInput = new ObjectInputStream(socket.getInputStream()); // read the username username = (String) sInput.readObject(); display(username + " just connected."); } catch (IOException e) { display("Exception creating new Input/output Streams: " + e); return; } // have to catch ClassNotFoundException // but I read a String, I am sure it will work catch (ClassNotFoundException e) { } date = new Date().toString() + "\n"; } 

Serveur d’images

 public class GreetingServer { public final static int SOCKET_PORT = 13267; // you may change this public final static Ssortingng FILE_TO_SEND = "C:/Users/Barry/Desktop/Duck.jpg"; // you may change this public static void main (Ssortingng [] args ) throws IOException { FileInputStream fis = null; BufferedInputStream bis = null; OutputStream os = null; ServerSocket servsock = null; Socket sock = null; try { servsock = new ServerSocket(SOCKET_PORT); while (true) { System.out.println("Waiting..."); try { sock = servsock.accept(); System.out.println("Accepted connection : " + sock); // send file File myFile = new File (FILE_TO_SEND); byte [] mybytearray = new byte [(int)myFile.length()]; fis = new FileInputStream(myFile); bis = new BufferedInputStream(fis); bis.read(mybytearray,0,mybytearray.length); os = sock.getOutputStream(); System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)"); os.write(mybytearray,0,mybytearray.length); os.flush(); System.out.println("Done."); } finally { if (bis != null) bis.close(); if (os != null) os.close(); if (sock!=null) sock.close(); } } } finally { if (servsock != null) servsock.close(); } } } 

Pour placer deux types de données sur le même socket, vous devez en quelque sorte distinguer les deux types de données. Puisque vous utilisez de toute façon des stream d’object / sortie d’object, l’utilisation des deux classes semble être un bon moyen de distinguer. Utilisez isAssignableFrom pour trouver chaque object.

 public static class ChatText implements Serializable { private Ssortingng text; /** * Get the value of text * * @return the value of text */ public Ssortingng getText() { return text; } /** * Set the value of text * * @param text new value of text */ public void setText(Ssortingng text) { this.text = text; } } 

 public static class PictureData implements Serializable { private byte[] data; /** * Get the value of data * * @return the value of data */ public byte[] getData() { return data; } /** * Set the value of data * * @param data new value of data */ public void setData(byte[] data) { this.data = data; } } 

 public static void main(Ssortingng[] args) { try { // Server implemented here ExecutorService es = Executors.newFixedThreadPool(4); ServerSocket ss = new ServerSocket(1234); es.submit(() -> { while (true) { Socket s = ss.accept(); es.submit(() -> { ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); while (true) { Object o = ois.readObject(); if (PictureData.class.isAssignableFrom(o.getClass())) { PictureData pd = (PictureData) o; System.out.println("got picture:" + Arrays.toSsortingng(pd.getData())); // Do something with picture here. } else if (ChatText.class.isAssignableFrom(o.getClass())) { ChatText ct = (ChatText) o; System.out.println("got text:" + ct.getText()); // Do something with chat here. } } }); } }); // Client implemented here, just for Testing Socket s = new Socket("localhost", 1234); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); ChatText ct = new ChatText(); ct.setText("first chat"); oos.writeObject(ct); //In a real client, the next three lines would be in a separate // class/function attached to some event handler. PictureData pd = new PictureData(); pd.setData(new byte[]{1, 2, 3, 4}); oos.writeObject(pd); Thread.sleep(2000); // ugly hack to make sure server doesn't close too early, for testing only es.shutdownNow(); s.close(); ss.close(); } catch (IOException | InterruptedException ex) { ex.printStackTrace(); } } 

Un vrai client mettrait la section que j’ai marquée dans le fichier principal et l’exécuter depuis un gestionnaire d’événement. Plus comme ça:

 public class MyClient extends JFrame { MyClient(Ssortingng host, int port) { try { Socket s= new Socket(host,port); JButton myButton = new JButton("Send Picture"); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); myButton.addActionListener(e -> { try { // Copy of code from previous example. PictureData pd = new PictureData(); pd.setData(new byte[]{1, 2, 3, 4}); oos.writeObject(pd); } catch (IOException ex) { ex.printStackTrace(); } }); add(myButton); pack(); setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(Ssortingng[] args) { java.awt.EventQueue.invokeLater(() -> new MyClient("localhost",1234)); } }