Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用applet实现客户机与服务器的通信_Java_Sockets_Applet_Socketexception - Fatal编程技术网

Java 用applet实现客户机与服务器的通信

Java 用applet实现客户机与服务器的通信,java,sockets,applet,socketexception,Java,Sockets,Applet,Socketexception,我对客户机-服务器编程比较陌生,我试图在applet gui上实现客户机和服务器之间的简单通信,它现在可以工作了,但是当我运行客户机时,我遇到了一个异常 修改代码: 客户: import java.awt.*; import java.net.*; import java.io.*; import javax.swing.*; public class Client extends JApplet{ /** * */ private static f

我对客户机-服务器编程比较陌生,我试图在applet gui上实现客户机和服务器之间的简单通信,它现在可以工作了,但是当我运行客户机时,我遇到了一个异常

修改代码:

客户:

import java.awt.*;
import java.net.*;
import java.io.*;

import javax.swing.*;


public class Client extends JApplet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JTextArea displayArea;
    private Socket socket = null;
    private DataInputStream input;
    private DataOutputStream output;


    public void init()
    {

        Container container = getContentPane();

        // set up JTextArea to display
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        container.add(new JScrollPane(displayArea), BorderLayout.SOUTH );

        try 
        {
            // make connection
            socket = new Socket(getCodeBase().getHost(), 5423);

            // get streams
            input = new DataInputStream( socket.getInputStream() );
            output = new DataOutputStream( socket.getOutputStream() ); 


            while(true) 
            {
                output.writeUTF("hello from client"); //send message to server
                output.flush(); 

                processMessage(input.readUTF()); //process data from server    
            }
        }
        // catch problems setting up connection and streams
        catch ( IOException ioException ) {
            ioException.printStackTrace(); 
        }

        try 
        {
            input.close();
            output.close();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    // process message received by client
    private void processMessage(String message)
    {
        if (message.equals("hello") ) 
        {
            displayMessage("Connected to server");
        }
    }


    private void displayMessage(final String messageToDisplay)
    {

        SwingUtilities.invokeLater(
                new Runnable() {  

                    public void run() 
                    {
                        displayArea.append(messageToDisplay);
                        displayArea.setCaretPosition(displayArea.getText().length());
                    }
                } 
            ); 
    }

}
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

public class Client extends JApplet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JTextArea displayArea;
    private Socket socket = null;
    private DataInputStream input;
    private DataOutputStream output;

    @Override
    public void init()
    {
        Container container = getContentPane();

        // set up JTextArea to display
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        container.add(new JScrollPane(displayArea), BorderLayout.SOUTH );

        try 
        {   
            // make connection
            socket = new Socket(getCodeBase().getHost(), 8020);

            // get streams
            input = new DataInputStream( socket.getInputStream() );
            output = new DataOutputStream( socket.getOutputStream() ); 

            output.writeUTF("hello from client"); //send message to server  

            processMessage(input.readUTF()); //process data from server     
        }
        // catch problems setting up connection and streams
        catch (IOException e) 
        {
            e.printStackTrace(); 
        }
    }


    // process message received by client
    private void processMessage(String message) throws IOException
    {
        if (message.equals("hello") ) 
        {
            displayMessage("Connected to server");      
        }
    }

    private void displayMessage(final String messageToDisplay)
    {

        SwingUtilities.invokeLater(
                new Runnable() {  

                    public void run() 
                    {
                        displayArea.append(messageToDisplay);
                        displayArea.setCaretPosition(displayArea.getText().length());
                    }
                } 
            ); 
    }

}
服务器:

import java.awt.*;
import java.net.*;
import java.io.*;

import javax.swing.*;


public class Server extends JFrame{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private ServerSocket serverSocket;
    private JTextArea outputArea;
    private Socket socket = null;
    private DataInputStream input;
    private DataOutputStream output;


    public Server()
    {

        super("Server");

        try
        {
            serverSocket = new ServerSocket(5423, 1);
        }
        catch(IOException ioException)
        {
            ioException.printStackTrace();
            System.exit(1);
        }


        outputArea = new JTextArea();
        getContentPane().add(outputArea, BorderLayout.CENTER);
        outputArea.setText("Server awaiting connections\n");


        setSize(300, 300);
        setVisible(true);
    }


    private void doThis() throws IOException
    {
        try
        {
            while(true)
            {

                socket = serverSocket.accept();

                input = new DataInputStream(socket.getInputStream());
                output = new DataOutputStream(socket.getOutputStream());

                output.writeUTF("hello");
                outputArea.append(input.readUTF()); //receive data from client
                output.flush();     
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            output.close();
            input.close();
            socket.close(); //close connection to client
        }
    }


    public static void main(String[] args) throws IOException 
    {
        Server server = new Server();   
        server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        server.doThis();    
    }
}
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;


public class Server extends JFrame{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JTextArea outputArea;
    private DataInputStream input;
    private DataOutputStream output;


    public Server()
    {
        super("Server");    

        outputArea = new JTextArea();
        getContentPane().add(outputArea, BorderLayout.CENTER);

        SwingUtilities.invokeLater(
                new Runnable() {  

                    public void run() 
                    {
                        outputArea.setText("Server awaiting connections\n");
                    }
                } 
            ); 


        setSize(300, 300);
        setVisible(true);
    }


    private void doThis() throws IOException
    {
        ServerSocket serverSocket = null;
        Socket socket = null;

        try
        {
            serverSocket = new ServerSocket(8020, 1);
        }
        catch(IOException ioException)
        {
            ioException.printStackTrace();
            System.exit(1);
        }


        try
        {
            while(true)
            {
                socket = serverSocket.accept();

                input = new DataInputStream(socket.getInputStream());
                output = new DataOutputStream(socket.getOutputStream());

                output.writeUTF("hello"); //send a string to client
                outputArea.append(input.readUTF()); //receive data from client and append the string to the text area


            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        finally 
        {
            socket.close();
        } 
    }


    public static void main(String[] args) 
    {
        new Thread(new Runnable() 
        {
            @Override
            public void run() 
            { 

                Server server = new Server();   
                server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                try 
                {
                    server.doThis();        
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }   

            }
        }).start();
    }
}
例外情况如下:

java.net.SocketException:在 java.net.SocketInputStream.read(未知源代码)位于 java.net.SocketInputStream.read(未知源代码)位于 java.net.SocketInputStream.read(未知源代码)位于 位于的java.io.DataInputStream.readUnsignedShort(未知源) 位于的java.io.DataInputStream.readUTF(未知源) 位于的java.io.DataInputStream.readUTF(未知源) Client.init(Client.java:45)位于sun.applet.AppletPanel.run(未知 源代码)位于java.lang.Thread.run(未知源代码)


现在您的服务器出现故障。
ServerSocket应该创建一次(就像在代码中一样),
然后ServerSocket listener应该等待接受新连接-每个客户端一个,只有当新客户端尝试连接时才会发生,

接受新客户端连接()时,新线程应处理每个客户端,在该线程中,您应打开IO流一次,然后创建一个读取/写入/处理数据的循环,同样,在数据处理循环完成后,IO流只应关闭一次。

尝试接受发布的建议,这次没有例外

客户:

import java.awt.*;
import java.net.*;
import java.io.*;

import javax.swing.*;


public class Client extends JApplet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JTextArea displayArea;
    private Socket socket = null;
    private DataInputStream input;
    private DataOutputStream output;


    public void init()
    {

        Container container = getContentPane();

        // set up JTextArea to display
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        container.add(new JScrollPane(displayArea), BorderLayout.SOUTH );

        try 
        {
            // make connection
            socket = new Socket(getCodeBase().getHost(), 5423);

            // get streams
            input = new DataInputStream( socket.getInputStream() );
            output = new DataOutputStream( socket.getOutputStream() ); 


            while(true) 
            {
                output.writeUTF("hello from client"); //send message to server
                output.flush(); 

                processMessage(input.readUTF()); //process data from server    
            }
        }
        // catch problems setting up connection and streams
        catch ( IOException ioException ) {
            ioException.printStackTrace(); 
        }

        try 
        {
            input.close();
            output.close();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    // process message received by client
    private void processMessage(String message)
    {
        if (message.equals("hello") ) 
        {
            displayMessage("Connected to server");
        }
    }


    private void displayMessage(final String messageToDisplay)
    {

        SwingUtilities.invokeLater(
                new Runnable() {  

                    public void run() 
                    {
                        displayArea.append(messageToDisplay);
                        displayArea.setCaretPosition(displayArea.getText().length());
                    }
                } 
            ); 
    }

}
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

public class Client extends JApplet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JTextArea displayArea;
    private Socket socket = null;
    private DataInputStream input;
    private DataOutputStream output;

    @Override
    public void init()
    {
        Container container = getContentPane();

        // set up JTextArea to display
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        container.add(new JScrollPane(displayArea), BorderLayout.SOUTH );

        try 
        {   
            // make connection
            socket = new Socket(getCodeBase().getHost(), 8020);

            // get streams
            input = new DataInputStream( socket.getInputStream() );
            output = new DataOutputStream( socket.getOutputStream() ); 

            output.writeUTF("hello from client"); //send message to server  

            processMessage(input.readUTF()); //process data from server     
        }
        // catch problems setting up connection and streams
        catch (IOException e) 
        {
            e.printStackTrace(); 
        }
    }


    // process message received by client
    private void processMessage(String message) throws IOException
    {
        if (message.equals("hello") ) 
        {
            displayMessage("Connected to server");      
        }
    }

    private void displayMessage(final String messageToDisplay)
    {

        SwingUtilities.invokeLater(
                new Runnable() {  

                    public void run() 
                    {
                        displayArea.append(messageToDisplay);
                        displayArea.setCaretPosition(displayArea.getText().length());
                    }
                } 
            ); 
    }

}
服务器:

import java.awt.*;
import java.net.*;
import java.io.*;

import javax.swing.*;


public class Server extends JFrame{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private ServerSocket serverSocket;
    private JTextArea outputArea;
    private Socket socket = null;
    private DataInputStream input;
    private DataOutputStream output;


    public Server()
    {

        super("Server");

        try
        {
            serverSocket = new ServerSocket(5423, 1);
        }
        catch(IOException ioException)
        {
            ioException.printStackTrace();
            System.exit(1);
        }


        outputArea = new JTextArea();
        getContentPane().add(outputArea, BorderLayout.CENTER);
        outputArea.setText("Server awaiting connections\n");


        setSize(300, 300);
        setVisible(true);
    }


    private void doThis() throws IOException
    {
        try
        {
            while(true)
            {

                socket = serverSocket.accept();

                input = new DataInputStream(socket.getInputStream());
                output = new DataOutputStream(socket.getOutputStream());

                output.writeUTF("hello");
                outputArea.append(input.readUTF()); //receive data from client
                output.flush();     
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            output.close();
            input.close();
            socket.close(); //close connection to client
        }
    }


    public static void main(String[] args) throws IOException 
    {
        Server server = new Server();   
        server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        server.doThis();    
    }
}
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;


public class Server extends JFrame{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JTextArea outputArea;
    private DataInputStream input;
    private DataOutputStream output;


    public Server()
    {
        super("Server");    

        outputArea = new JTextArea();
        getContentPane().add(outputArea, BorderLayout.CENTER);

        SwingUtilities.invokeLater(
                new Runnable() {  

                    public void run() 
                    {
                        outputArea.setText("Server awaiting connections\n");
                    }
                } 
            ); 


        setSize(300, 300);
        setVisible(true);
    }


    private void doThis() throws IOException
    {
        ServerSocket serverSocket = null;
        Socket socket = null;

        try
        {
            serverSocket = new ServerSocket(8020, 1);
        }
        catch(IOException ioException)
        {
            ioException.printStackTrace();
            System.exit(1);
        }


        try
        {
            while(true)
            {
                socket = serverSocket.accept();

                input = new DataInputStream(socket.getInputStream());
                output = new DataOutputStream(socket.getOutputStream());

                output.writeUTF("hello"); //send a string to client
                outputArea.append(input.readUTF()); //receive data from client and append the string to the text area


            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

        finally 
        {
            socket.close();
        } 
    }


    public static void main(String[] args) 
    {
        new Thread(new Runnable() 
        {
            @Override
            public void run() 
            { 

                Server server = new Server();   
                server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                try 
                {
                    server.doThis();        
                } 
                catch (IOException e) 
                {
                    e.printStackTrace();
                }   

            }
        }).start();
    }
}

例外情况是什么?嗨,我已经编辑了主要帖子,包括第41行附近的代码例外情况。这里发生了什么?再次查看抛出异常的行上方的第41-5行。你看到了什么?为什么要关闭循环中的IO流?在处理完所有数据后,应该只执行一次。我注意到,我不应该关闭客户端上的流,因为服务器正在请求返回字符串,我已经更改了它,以便在服务器上关闭流。我还删除了“while true”循环,因为它在这里没有任何用途,所以现在我没有得到任何异常。过一段时间,我会试着给自己的问题贴一个完整的答案,如果你认为我仍然在做一些奇怪的事情,如果你能编辑我的答案,我将不胜感激。