douhe4608 2013-10-11 01:21
浏览 52
已采纳

Java Socket侦听器问题?

I have been stuck on this for a while now. I am trying to send data to the Java, server with PHP. When i load the plugin in Bukkit, it stops loading when i call this function:

public void SocketListen()
{       

    String clientSentence;
    String capitalizedSentence;

    try
    {

        ServerSocket welcomeSocket = new ServerSocket(25566);

        while(true)
        {
           Socket connectionSocket = welcomeSocket.accept();
           BufferedReader inFromClient =
              new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
           DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
           clientSentence = inFromClient.readLine();
           System.out.println("Received: " + clientSentence);
           capitalizedSentence = clientSentence.toUpperCase() + '
';
           outToClient.writeBytes(capitalizedSentence);
        }
    }
    catch(IOException e)
    {
        getLogger().severe(e.toString());
    }

}

which tells me i did something wrong. My PHP is:

<?php
$host = "localhost"; 
$port = 25566;
$data = 'test
';

if ( ($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE )
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error());
else 
{
    echo "Attempting to connect to '$host' on port '$port'...<br>";
    if ( ($result = socket_connect($socket, $host, $port)) === FALSE )
        echo "socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error($socket));
    else {
        echo "Sending data...<br>";
        socket_write($socket, $data, strlen($data));
        echo "OK<br>";

        echo "Reading response:<br>";
        while ($out = socket_read($socket, 2048)) {
            echo $out;
        }
    }
    socket_close($socket);      
}
?>

What am i doing wrong?

Basically, i just need the PHP server to send "Hello" then the Java Client Spit it out with getLogger().info(data);

Also, do i need to Port forward 25566 on the Client or the server with PHP? They are both hosted on my Local Network with the same External IP.

  • 写回答

1条回答 默认 最新

  • douben6670 2013-12-26 01:19
    关注

    This may be due to the fact that the loop never stops:

     while(true)
        {
          //code
    

    you can use the class i made for java server and clients:

    ChatCleint

        package com.weebly.foxgenesis.src;
    import java.net.*;
    import java.io.*;
    
    public final class ChatClient
    {  
        private Socket socket = null;
        private DataOutputStream streamOut = null;
        private ChatClientThread client = null;
        private String serverName = "localhost";
        private int serverPort = -1;
        private final ChatReciever output;
    
    /**
     * Create a new ChatClient that connects to a given server and receives UTF-8 encoded messages
     * @param a Client class
     */
    public ChatClient(ChatReciever chatReciever)
    { 
        output = chatReciever;
        serverPort = chatReciever.getPort();
        serverName = chatReciever.getHost();
        connect(serverName, serverPort);
    }
    
    private void connect(String serverName, int serverPort)
    {  
        output.handleLog("Establishing connection. Please wait ...");
        try
        {  
            socket = new Socket(serverName, serverPort);
            output.handle("Connected to chat server");
            open();
        }
        catch(UnknownHostException uhe)
        {  
            output.handleError("Host unknown: " + uhe.getMessage()); 
        }
        catch(IOException ioe)
        {  
            output.handleError("Unexpected exception: " + ioe.getMessage()); 
        } 
    }
    
    /**
     * Sends a message to the server through bytes in UTF-8 encoding 
     * @param msg message to send to the server
     */
    public void send(String msg) throws IOException
    {  
        streamOut.writeUTF(msg); 
        streamOut.flush();
    }
    
    /**
     * forces the ChatReciever to listen to a message (NOTE: this does not send anything to the server)
     * @param msg message to send
     */
    public void handle(String msg)
    {  
        output.handle(msg);
    }
    
    private void open() throws IOException
    {   
        streamOut = new DataOutputStream(socket.getOutputStream());
        client = new ChatClientThread(this, socket); 
    }
    
    /**
     * tries to close 
     */
    public void close() throws IOException
    {  
        if (streamOut != null)  
            streamOut.close();
        if (socket    != null)  
            socket.close(); 
    }
    
    /**
     * closes the client connection
     */
    @SuppressWarnings("deprecation")
    public void stop()
    {
        if(client != null)
            client.stop();
        client = null;
    }
    
    /**
     * checks if the ChatClient is currently connected to the server
     * @return Boolean is connected
     */
    public boolean isConnected()
    {
        return client == null ?(false) : (true);
    }
    }
    

    ChatServerThread

       package com.weebly.foxgenesis.src;
    
    
    
    import java.net.*;
    import java.io.*;
    
    public final class ChatClientThread extends Thread
    {  
        private Socket           socket   = null;
        private ChatClient       client   = null;
        private DataInputStream  streamIn = null;
    
        public ChatClientThread(ChatClient _client, Socket _socket)
        {  
            client   = _client;
            socket   = _socket;
            open();  
            start();
        }
        public void open()
        {  
            try
            {  
                streamIn  = new DataInputStream(socket.getInputStream());
            }
            catch(IOException ioe)
            {  
                System.out.println("Error getting input stream: " + ioe);
                client.stop();
            }
        }
        public void close()
        {  
            try
            {  
                if (streamIn != null) streamIn.close();
            }
            catch(IOException ioe)
            {  
                System.out.println("Error closing input stream: " + ioe);
            }
        }
        public void run()
        {  
            while (true)
            {  
                try
                {  
                    client.handle(streamIn.readUTF());
                }
                catch(IOException ioe)
                { 
                    System.out.println("Listening error: " + ioe.getMessage());
                    client.stop();
                }
            }
        }
    }
    

    ChatReciever

     package com.weebly.foxgenesis.src;
    
    public interface ChatReciever 
    {
        /**
         * gets the IP address of the host
         * @return String IP address
         */
        public String getHost();
    
        /**
         * gets the port of the host
         * @return Integer port of host
         */
        public int getPort();
    
        /**
         * sends a message from the server to the implementing class
         * @param msg message from the server
         */
        public void handle(String msg);
    
        /**
         * sends an error to the implementing class
         * @param errorMsg error message
         */
        public void handleError(String errorMsg);
    
        /**
         * Sends a message to the log
         * @param msg message to send
         */
        public void handleLog(Object msg);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP