Sockets Problem

Discussion in 'Plugin Development' started by chriztopia, Jun 26, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    chriztopia

    I have added this code to my plugin for a socket server what I want to do is very simple listen for a command then process it. The problem is it is not converting the incoming to a string and it is also looping the info nonstop causing read timeout errors... If anyone can help me solve the problem that would be great or give me a new code to use that will work the same... I am also attempting for now to send the info by php just to make sure it works it will be in an android app when I am finished.

    Code:
              ServerSocket server = null;
              try
              {
                server = new ServerSocket(5555);
              }
              catch (IOException e)
              {
                System.out.println("Error on port: 5555 " + ", " + e);
                System.exit(1);
              }
     
              System.out.println("Server setup and waiting for client connection ...");
     
              Socket client = null;
              try
              {
                client = server.accept();
              }
              catch (IOException e)
              {
                System.out.println("Did not accept connection: " + e);
                System.exit(1);
              }
     
              System.out.println("Client connection accepted. Moving to local port ...");
     
              try
              {
                DataInputStream streamIn = new
                          DataInputStream(new
                          BufferedInputStream(client.getInputStream()));
     
                boolean done = false;
                String line;
                while (!done)
                {
                    line = streamIn.toString();
                    if (line.equalsIgnoreCase(".bye"))
                      done = true;
                    else
                      System.out.println("Client says: " + line);
                }
     
                streamIn.close();
                client.close();
                server.close();
              }
              catch(IOException e)
              { System.out.println("IO Error in streams " + e); }
         
    
    Code:
    <?php
     
    $fp = fsockopen("SERVER.com",5555,$errno,$errstr,5);
    if (!$fp)
    {
        echo $errstr." (".$errno.")";
    }
    else
    {
        $out = "heal player\r\n";
            $out .= ".bye";
        fwrite($fp,$out);
     
        fclose($fp);
    }
     
    ?> 
     
  2. Offline

    CoderCloud

    You can use a BufferedReader to read lines, the reader has a build in method for readLine()

    You can create the reader like this: 'new BufferedReader(new InputstreamReader(client.getInputstream()))'

    And use a new async Thread to read the data so you dont stop the bukkitserver while reading(Scheduler).
    Bukkit.getScheduler().runTaskAsynchronously(PLUGIN, THREAD)
     
  3. Offline

    chriztopia

    Ok So I have some code now that works good but I am having a problem with my connection staying open and being refused when I attempt to connect twice.

    Code:
    @Override
    public void onEnable()  {
        this.getServer().getPluginManager().registerEvents(new ServerChatPlayerListener(this), this);
    //===========
       
        getServer().getScheduler().runTaskAsynchronously(this, new Runnable() {
            @Override
            public void run() {
                server = new Server(5555);
     
            try {
            Thread.sleep(1000);
            } catch (InterruptedException e) {
            e.printStackTrace();
            }
            }
            });
     
       
        //===========
    }
    Code:
    import java.io.*;
    import java.net.*;
     
    public class Server {
        public Server(int port) {
            try {
                setUpServer(port);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       
     
        private void setUpServer(int port) throws Exception {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(port);
            } catch (IOException e) {
                System.err.println("Could not listen on port: 5555.");
                //System.exit(1);
            }
     
            Socket clientSocket = null;
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException e) {
                System.err.println("Accept failed.");
                //System.exit(1);
            }
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    clientSocket.getInputStream()));
       
            out.println("Looks Good!");
           
           
            String[] loc = in.readLine().split(":");
           
            loc.toString();
            if (loc[0].equals("heal")){
                System.out.println("HEAL " + loc[1]) ;
            }
     
           
            PrintWriter out1 = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in1 = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out1.close();
            in1.close();
            clientSocket.close();
            serverSocket.close();
         
        }
    }
     
    
     
  4. Offline

    zack6849

    you can't connect twice because you need multithreading, when you have one client connected the main thread is caught up while processing all of its info, you need to make a dew thread for the socket and process it there
    Here's an example, pardon the messy and probably inefficient code
    Code:
     
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.io.Writer;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    public class Main
    { 
            public static void main(String[] args){
                try
                {
                    final ServerSocket server = new ServerSocket(1337);
                    System.out.println("Accepting connections...");
                    while(true){
                        final Socket client = server.accept();
                        System.out.println("Connection from " + client.getInetAddress().getHostName());
                        //spawn a new thread to handle said client, leaving the main thread free to accept new connections.
                        new Thread(new Runnable(){
                            @Override
                            public void run(){
                                try
                                {
                                    System.out.println("Setting up readers...");
                                    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                                    BufferedWriter out = new BufferedWriter(new PrintWriter(client.getOutputStream()));
                                    System.out.println("Done!");
                                    send(out, "Hello!");
                                    System.out.println("Sent welcome line.");
                                    String tmp = "";
                                    while((tmp = in.readLine()) != null){
                                        //do your parsing and stuff here.
                                        send(out, ">>" + tmp);
                                    }
                                } catch (IOException ex)
                                {
                                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                                }
                            }
                        }).start();
                       
                       
                    }
                } catch (Exception ex)
                {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            } 
            public static void send(BufferedWriter out, String send){
                try
                {             
                    //requires a \r\n to make a newline
                    out.write(send + "\r\n");
                    //has to be flushed after all messages or they wont display
                    out.flush();
                } catch (IOException ex)
                {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    }
    
     
Thread Status:
Not open for further replies.

Share This Page