Jump to content

Using Java socket on minecraft


SmokingDude

Recommended Posts

Hello, I have a project that consists of linking several clients together without the mod being installed on the server, even if the players are on a different server the communication must be possible so I decided to use the Socket after several attempts it works the worry is that after calling the method to accept a connection on the server side, minecraft stops as if the main thread stopped when I close the vps minecraft resumes as if nothing was wrong, I use threads whether in client or server to make the connection and exchange information, is the socket the right way used if yes how could I do not stop the main thread of minecraft here are the client code and the server one 

  public ServerListener() {
       debug("Creating the server");
       clientList = new ArrayList<ConnectionToClient>();
       messages = new LinkedBlockingQueue<Object>();
       debug("Client list is created");
       try {
           serverSocket = new ServerSocket(2406);
           debug("opening the port 2406");
       } catch (IOException e) {
         e.printStackTrace();
           debug(e.getMessage());
       }
    debug("creating the accept thread");
       Thread accept = new Thread() {
           public void run() {
    debug("thread created");
               while (true) {
                   try {
                       Socket s = serverSocket.accept();
if(s!=null) {
                       debug("new client joined");
                       clientList.add(new ConnectionToClient(s));
                       debug("new client was accepted ["+ s.getInetAddress() + "/" + s.getPort()+"]");
                
}
 } catch (IOException e) {
                       e.printStackTrace();
                      debug(e.getMessage());
                   }
               }
           }
       };
       accept.setDaemon(true);
       accept.start();

       Thread messageHandling = new Thread() {
           public void run() {
               while (true) {
                   try {
                       Object message = messages.take();
                       debug("we parse the ping");
                       parse(message);
                       System.out.println("Message Received: " + message);
                   } catch (InterruptedException e) {
                   }
               }
           }
       };

       messageHandling.setDaemon(true);
       messageHandling.start();
   }

   private void parse(Object message) {
       String msg = String.valueOf(message);
       if(msg.contains("-")) {
           if(msg.contains("key")) {
               debug("key detected");
               key = msg.split("-")[1];
           } else if(msg.contains("name")) {
               debug("name detected");
               name = msg.split("-")[1];
           } else if(msg.contains("world")) {
               debug("worldname detected");
               world = msg.split("-")[1];
           } else if(msg.contains("server")) {
               debug("servername detected");
               server = msg.split("-")[1];
           } else if(msg.contains("x")) {
               debug("x detected");
               x = Integer.parseInt(msg.split("-")[1]);
           } else if(msg.contains("y")) {
           debug("y detected");
               y = Integer.parseInt(msg.split("-")[1]);
           } else if(msg.contains("z")) {
                debug("z detected");
               z = Integer.parseInt(msg.split("-")[1]);
           } else if(msg.contains("isEntity")) {
                   debug("entity detected");
               entity = msg.split("-")[1].equalsIgnoreCase("true");
           } else if(msg.contains("ticks")) {
               debug("ticks detected");
               lTicks = Integer.parseInt(msg.split("-")[1]);
           } else if(msg.contains("end")) {
               debug("we got everything detected");
               toSend = new IrcMPING(key, name, world, server, x, y, z, entity, lTicks);
               for(String str : toSend.getArgs()) {
                   
                   sendToAll(str);
               }
               toSend=null;
           }
       }
   }

   public void sendToOne(int index, Object message) throws IndexOutOfBoundsException {
       clientList.get(index).write(message);
   }

   public void sendToAll(Object message) {
       for (ConnectionToClient client : clientList) {
           debug("sending the ping to " + client.socket.getInetAddress());
           client.write(message);
       }
   }

   public void debug(String str) {
           System.out.println("SOROS DEBUG [MULTIPING] : " + str) ;
     
       }

   private class ConnectionToClient {
       ObjectInputStream in;
       ObjectOutputStream out;
       Socket socket;

       ConnectionToClient(Socket socket) throws IOException {
           this.socket = socket;
           in = new ObjectInputStream(socket.getInputStream());
           out = new ObjectOutputStream(socket.getOutputStream());

           Thread read = new Thread() {
               public void run() {
                   while (true) {
                       try {
                           Object obj = in.readObject();
                           messages.put(obj);
                       } catch (IOException e) {
                           e.printStackTrace();
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       } catch (ClassNotFoundException e) {
                           e.printStackTrace();
                       }
                   }
               }
           };

           read.setDaemon(true); // terminate when main ends
           read.start();
       }

       public void write(Object obj) {
           try {
     
               out.writeObject(obj);
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       
    
   }

}
public IRCClient() throws IOException {
        socket = new Socket(InetAddress.getByAddress(new byte[]{(byte) 185, (byte) 242, (byte) 180,97}), 2406);
        messages = new LinkedBlockingQueue<Object>();
        server = new ConnectionToServer(socket);

        Thread messageHandling = new Thread() {
            public void run() {
                while (true) {
                    try {
                        Object message = messages.take();
                        parse(message);
                        System.out.println("Message Received: " + message);
                    } catch (InterruptedException e) {
                    }
                }
            }
        };

        messageHandling.setDaemon(true);
        messageHandling.start();
    }

    private void parse(Object message) {
        String msg = String.valueOf(message);
        if (msg.contains("-")) {
            if (msg.contains("key")) {
                key = msg.split("-")[1];
            } else if (msg.contains("name")) {
                name = msg.split("-")[1];
            } else if (msg.contains("world")) {
                world = msg.split("-")[1];
            } else if (msg.contains("server")) {
                serverName = msg.split("-")[1];
            } else if (msg.contains("x")) {
                x = Integer.parseInt(msg.split("-")[1]);
            } else if (msg.contains("y")) {
                y = Integer.parseInt(msg.split("-")[1]);
            } else if (msg.contains("z")) {
                z = Integer.parseInt(msg.split("-")[1]);
            } else if (msg.contains("isEntity")) {
                entity = msg.split("-")[1].equalsIgnoreCase("true");
            } else if (msg.contains("ticks")) {
                lTicks = Integer.parseInt(msg.split("-")[1]);
            } else if (msg.contains("end")) {
                if (key.equalsIgnoreCase(MultiPingMod.getKey()) && !name.equalsIgnoreCase(Minecraft.getMinecraft().thePlayer.getName())) {
                    MultiPing m = new MultiPing(name, world, serverName, x, y, z, entity);
                    MultiPingMod.setTime(lTicks);
                    m.render = true;
                    if (MultiPingMod.render.getToRender().containsKey(name)) {
                        MultiPingMod.render.getToRender().get(name).render = false;
                        MultiPingMod.render.getToRender().remove(name);
                    }
                    MultiPingMod.render.addToRender(m);
                }
            }
        }
    }

    public void send(Object obj) {
        server.write(obj);
    }

    private class ConnectionToServer {
        ObjectInputStream in;
        ObjectOutputStream out;
        Socket socket;

        ConnectionToServer(Socket socket) throws IOException {
            this.socket = socket;
            in = new ObjectInputStream(socket.getInputStream());
            out = new ObjectOutputStream(socket.getOutputStream());

            Thread read = new Thread() {
                public void run() {
                    while (true) {
                        try {
                            Object obj = in.readObject();
                            messages.put(obj);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };

            read.setDaemon(true);
            read.start();
        }

        private void write(Object obj) {
            try {
                out.writeObject(obj);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

 

Link to comment
Share on other sites

4 hours ago, diesieben07 said:

Using raw threads, raw sockets, ObjectOutputStream and terrible exception handling. All of these are no-gos. You should use Netty.

So netty allow me to communicate between my minecraft and a distant vps right ? There is some way to use it with forge or should i use it like i can use it on normal Java programme ? 

Link to comment
Share on other sites

5 hours ago, diesieben07 said:

Netty is a library for network communication. Minecraft already uses it for its networking so you can "just use it".

I implémented Netty everything seems working the server actually receive the connection of the client but the game still stop when i connect to the server, how am I supposed to use Netty to get minecraft working ? 

The client part source : https://pastebin.com/v5dN94BJ

Edited by SmokingDude
Link to comment
Share on other sites

Yes i have a class called '' KeybindListener '' And inside I have this method :

@SubscribeEvent

public void onKeyPress(InputEvent.KeyInputEvent event) { if(Keyboard.isKeyDown(Keyboard.KEY_R))

if(irc==null) {

irc = new IRCClient(''samuele.site'',2406);

irc.run();

}

showgui();

}

 

I do register this class with MinecraftForge.EVENT_BUS.register(new KeybindListener()) ;

Quote

 

Edited by SmokingDude
Link to comment
Share on other sites

17 minutes ago, diesieben07 said:

So you are running the network code inside a key press event handler.

Which means you are blocking the main thread while the network code runs (forever).

So where i am supposed to run it ? Because I dont see any other way doing it on the init of the mod make minecraft stop on the loading forge screen, can you help me or give me a lead please? 

Link to comment
Share on other sites

On 4/22/2021 at 4:01 PM, diesieben07 said:

For example, yes.

I tried I mean I succeeded and until then there's no more worries the server gets the connection, minecraft no longer stops, but I can not communicate between the client and the server, the client must send a certain string to the server when it performs a specific action no matter how I do it (synchronised irc or synchronised boolean etc the client never sends anything to the server, would you have a lead on what I need to do to get to settle this please) 

Link to comment
Share on other sites

Yes sorry for my bad english, on the IRCClient class i have a method called '' send '' who basically send a string to the server, this method is called from the KeybindListener when the player hit the '' R '' key, When the server receives a message it is supposed to write ''message received from the client : the message '' But the server does not print anything in the terminal which means that it receives nothing and I think it comes from the fact that IRCClient is declared in a different thread to the thread in which the keyinput event is, and I do not know how to be able to call 'send' from the thread for it to works 

Edited by SmokingDude
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Detik4D adalah situs slot 4D resmi yang menawarkan pengalaman bermain yang mengasyikkan dan peluang menang besar. Dengan koleksi permainan slot yang beragam dan fitur-fitur menarik, Detik4D menjadi pilihan utama bagi para pecinta slot online. Peluang Menang Besar dengan Jackpot Resmi Salah satu keunggulan utama Detik4D adalah peluang menang besar yang ditawarkan. Dengan sistem jackpot resmi, para pemain memiliki kesempatan untuk memenangkan hadiah besar yang dapat mengubah hidup mereka. Jackpot-jackpot ini tidak hanya menghadirkan keseruan tambahan dalam bermain, tetapi juga memberikan peluang nyata untuk meraih keuntungan yang signifikan. Detik4D juga memiliki berbagai macam permainan slot dengan tingkat pembayaran yang tinggi. Dengan demikian, peluang untuk meraih kemenangan dalam jumlah besar semakin terbuka lebar. Para pemain dapat memilih dari berbagai jenis permainan slot yang menarik, termasuk slot klasik, video slot, dan slot progresif. Setiap jenis permainan memiliki fitur-fitur unik dan tema yang berbeda, sehingga para pemain tidak akan pernah merasa bosan. Pengalaman Bermain yang Mengasyikkan Selain peluang menang besar, Detik4D juga menawarkan pengalaman bermain yang mengasyikkan. Dengan tampilan grafis yang menarik dan suara yang menghibur, para pemain akan merasa seperti berada di kasino sungguhan. Fitur-fitur interaktif seperti putaran bonus, putaran gratis, dan fitur-fitur lainnya juga akan menambah keseruan dalam bermain. Detik4D juga memiliki antarmuka yang user-friendly, sehingga para pemain dapat dengan mudah mengakses permainan dan fitur-fitur lainnya. Proses pendaftaran dan deposit juga sangat mudah dan cepat, sehingga para pemain dapat segera memulai petualangan mereka di dunia slot online. Detik4D juga menyediakan layanan pelanggan yang responsif dan profesional. Tim dukungan pelanggan yang ramah akan siap membantu para pemain dengan segala pertanyaan atau masalah yang mereka hadapi. Dengan demikian, para pemain dapat bermain dengan tenang dan yakin bahwa mereka akan mendapatkan bantuan yang mereka butuhkan. Keamanan dan Kepercayaan Detik4D sangat memprioritaskan keamanan dan kepercayaan para pemain. Situs ini menggunakan teknologi enkripsi terkini untuk melindungi data pribadi dan transaksi keuangan para pemain. Selain itu, Detik4D juga bekerja sama dengan penyedia permainan terkemuka yang telah teruji dan terpercaya, sehingga para pemain dapat bermain dengan aman dan adil. Detik4D juga memiliki lisensi resmi dan diatur oleh otoritas perjudian yang terkemuka. Hal ini menjamin bahwa semua permainan yang ditawarkan adalah fair dan tidak ada kecurangan yang terjadi. Para pemain dapat bermain dengan tenang, mengetahui bahwa mereka berada di situs yang terpercaya dan terjamin. Jadi, jika Anda mencari situs slot 4D resmi dengan peluang menang besar dan pengalaman bermain yang mengasyikkan, Detik4D adalah pilihan yang tepat. Bergabunglah sekarang dan rasakan sendiri keseruan dan keuntungan yang ditawarkan oleh Detik4D.
    • Perjudian online telah menjadi tren yang populer di kalangan penggemar permainan kasino. Salah satu permainan yang paling diminati adalah mesin slot online. Mesin slot online menawarkan kesenangan dan kegembiraan yang tak tertandingi, serta peluang untuk memenangkan hadiah besar. Salah satu situs slot online resmi yang menarik perhatian banyak pemain adalah Tuyul Slot. Kenapa Memilih Tuyul Slot? Tuyul Slot adalah situs slot online resmi yang menawarkan berbagai keuntungan bagi para pemainnya. Berikut adalah beberapa alasan mengapa Anda harus memilih Tuyul Slot: 1. Keamanan dan Kepercayaan Tuyul Slot adalah situs slot online resmi yang terpercaya dan memiliki reputasi yang baik di kalangan pemain judi online. Situs ini menggunakan teknologi keamanan terkini untuk melindungi data pribadi dan transaksi keuangan pemain. Anda dapat bermain dengan tenang dan yakin bahwa informasi Anda aman. 2. Pilihan Permainan yang Beragam Tuyul Slot menawarkan berbagai macam permainan slot online yang menarik. Anda dapat memilih dari ratusan judul permainan yang berbeda, dengan tema dan fitur yang beragam. Setiap permainan memiliki tampilan grafis yang menarik dan suara yang menghibur, memberikan pengalaman bermain yang tak terlupakan. 3. Kemudahan Menang Salah satu keunggulan utama dari Tuyul Slot adalah kemudahan untuk memenangkan hadiah. Situs ini menyediakan mesin slot online dengan tingkat pengembalian yang tinggi, sehingga peluang Anda untuk memenangkan hadiah besar lebih tinggi. Selain itu, Tuyul Slot juga menawarkan berbagai bonus dan promosi menarik yang dapat meningkatkan peluang Anda untuk menang. Cara Memulai Bermain di Tuyul Slot Untuk memulai bermain di Tuyul Slot, Anda perlu mengikuti langkah-langkah berikut: 1. Daftar Akun Kunjungi situs Tuyul Slot dan klik tombol "Daftar" untuk membuat akun baru. Isi formulir pendaftaran dengan informasi pribadi yang valid dan lengkap. Pastikan untuk memberikan data yang akurat dan jaga kerahasiaan informasi Anda. 2. Deposit Dana Setelah mendaftar, Anda perlu melakukan deposit dana ke akun Anda. Tuyul Slot menyediakan berbagai metode pembayaran yang aman dan terpercaya. Pilih metode yang paling nyaman untuk Anda dan ikuti petunjuk untuk melakukan deposit. 3. Pilih Permainan Setelah memiliki dana di akun Anda, Anda dapat memilih permainan slot online yang ingin Anda mainkan. Telusuri koleksi permainan yang tersedia dan pilih yang paling menarik bagi Anda. Anda juga dapat mencoba permainan secara gratis sebelum memasang taruhan uang sungguhan. 4. Mulai Bermain Saat Anda sudah memilih permainan, klik tombol "Main" untuk memulai permainan. Anda dapat mengatur jumlah taruhan dan jumlah garis pembayaran sesuai dengan preferensi Anda. Setelah itu, tekan tombol "Putar" dan lihat apakah Anda beruntung untuk memenangkan hadiah. Promosi dan Bonus Tuyul Slot menawarkan berbagai promosi dan bonus menarik kepada para pemainnya. Beberapa jenis promosi yang tersedia termasuk bonus deposit, cashback, dan turnamen slot. Pastikan untuk memanfaatkan promosi ini untuk meningkatkan peluang Anda memenangkan hadiah besar. Kesimpulan Tuyul Slot adalah situs slot online resmi yang menawarkan pengalaman bermain yang seru dan peluang menang yang tinggi. Dengan keamanan dan kepercayaan yang terjamin, berbagai pilihan permainan yang menarik, serta bonus dan promosi yang menguntungkan, Tuyul Slot menjadi pilihan yang tepat bagi para penggemar mesin slot online. Segera daftar akun dan mulai bermain di Tuyul Slot untuk kesempatan memenangkan hadiah besar!
    • I have been having a problem with minecraft forge. Any version. Everytime I try to launch it it always comes back with error code 1. I have tried launching from curseforge, from the minecraft launcher. I have also tried resetting my computer to see if that would help. It works on my other computer but that one is too old to run it properly. I have tried with and without mods aswell. Fabric works, optifine works, and MultiMC works aswell but i want to use forge. If you can help with this issue please DM on discord my # is Haole_Dawg#6676
    • Add the latest.log (logs-folder) with sites like https://paste.ee/ and paste the link to it here  
    • I have no idea how a UI mod crashed a whole world but HUGE props to you man, just saved me +2 months of progress!  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.