0

我对客户端-服务器编程比较陌生,我试图在 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 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();    
    }
}

异常内容如下:

java.net.SocketException:连接重置在 java.net.SocketInputStream.read(Unknown Source) 在 java.net.SocketInputStream.read(Unknown Source) 在 java.io.DataInputStream 的 java.net.SocketInputStream.read(Unknown Source) .readUnsignedShort(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at Client.init(Client.java:45) at sun.applet.AppletPanel.run(未知来源)在 java.lang.Thread.run(未知来源)

4

2 回答 2

0

现在你的服务器有问题。
ServerSocket 应该创建一次(就像在您的代码中一样),
然后 ServerSocket 侦听器应该等待接受新连接 - 每个客户端一个,它仅在新客户端尝试连接时发生,
当新客户端连接被接受()时线程应该处理每个客户端,并且在该线程中,您应该打开一次 IO 流,然后创建一个循环读取/写入/处理数据,再次,IO 流应该只在数据处理循环完成后关闭一次。

于 2013-10-28T11:16:37.900 回答
0

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

客户:

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 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();
    }
}
于 2013-10-28T12:44:42.670 回答