关闭一个开放的Java服务器和客户端

时间:2014-06-18 18:35:59

标签: java android sockets

我有一个运行的java服务器和一个连接它的android客户端。我可以成功发送和接收来自第一个Android活动的数据。

我想要做的是,当我点击我的登录按钮(有效)时,我想关闭一个活动(主页)中的连接,停止服务器,重新启动服务器并打开一个新连接重定向页面。

当我关闭客户端的连接(并重新启动服务器)并在下一页重新启动客户端时,某些东西必定是错误的,因为我的服务器重新启动,但第二个android活动启动并连接到服务器,但从不接受或接收I / O流。我从来没有得到I / O流的确认。

可能是我在服务器中只创建一次套接字??

服务器

  public static void main(String[] args) 
  {
         SASSServer s = new SASSServer();
  }
  public SASSServer()
  { 
    try {
        BuildUI();
        setTitle("SASS Server");
        pack();
        setVisible(true);
    } catch (IOException ex) {
        Logger.getLogger(SASSServer.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  public void BuildUI() throws IOException
 {

    // create keypad
    JPanel p = new JPanel();

            /*
            enterField = new JTextField();
    enterField.setEnabled(true);

    enterField.addActionListener(

    new ActionListener() {
        // send message to client
        public void actionPerformed(ActionEvent event) {
            sendData(event.getActionCommand());
        }
    }

    );

            p.add(enterField);*/
       p.setLayout(new GridLayout(4, 1, 2, 2));

            ConnectServer = new JButton("Connect to server");
            p.add(ConnectServer);

            ConnectDatabase = new JButton("Connect to database");
            p.add(ConnectDatabase);

            CloseServer = new JButton("Close Server");
            p.add(CloseServer);

    add("Center", p);

             addWindowListener(this);
            addWindowFocusListener(this);
            addWindowStateListener(this);
            ConnectServer.addActionListener(this);
            ConnectDatabase.addActionListener(this);
            CloseServer.addActionListener(this);

            Create a ServerSocket.
        server = new ServerSocket(5001, 100);
  }
  public void runServer() throws Exception 
  {
    try 
            {

    while (true) {

            // Step 2: Wait for a connection.
            waitForConnection();

            // Step 3: Get input and output streams.
            getStreams();

            // Step 4: Process connection.
            processConnections();

            // Step 5: Close connection.
            closeConnection();
            ++counter;

        }
    } 
            catch (EOFException eofException) 
            {
        System.out.println("Client terminated connection");
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }

}

  // wait for connectionto arrive, then display connection info
   private void waitForConnection() throws IOException 
  {
    System.out.println("Waiting for connection\n");

    connection = server.accept();

    System.out.println("Connection " + counter + " received from: "
            + connection.getInetAddress().getHostName());
  }

  // get streams to send and receive data
  private void getStreams() throws IOException 
  {
        output = new ObjectOutputStream(connection.getOutputStream());

        output.flush();

        input = new ObjectInputStream(connection.getInputStream());

        System.out.println("\nGot I/O streams\n");
  }


   private void sendData(String message) 
   {
    try 
    {
            output.writeObject(message);
            output.flush();
            System.out.println("\nCLIENT>>>" + message);
    } 
    catch (IOException ioException) 
    {
            System.out.println("\nError writing object");
    }
  }

  // close streams and socket
  private void closeConnection() throws IOException 
   {
    try 
    {
        System.out.println("\nUser terminated connection");
        output.close();
        input.close();
        connection.close();
    } 
    catch (Exception ex) 
    {
        Logger.getLogger(SASSServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

  // process connection with client
public void processConnections() throws Exception
{
    String message = "SERVER>>> Connection successful";
        output.writeObject(message);
        output.flush();
        do 
        {
                try 
                {
                        message = (String) input.readObject();
                        if (message.equals("TERMINATE"))
                        {
                            closeConnection();
                            runServer();
                        }
                        else
                        {
                        System.out.println("XML string being created into document : " + message);
                        Document d = CreateDocumentFromString(message);
                        String xmlname = "ServerData.xml";
                        x.saveDoc(d, xmlname);
                        processXML(xmlname);            
                        System.out.println("Document " + xmlname + " has been created" );
                        System.out.println("\n Message: " + message);
                        }
                } 
                catch (ClassNotFoundException classNotFoundException) 
                {
                        System.out.println("\nUnknown object type received");
                }
        } 
        while (!message.equals("CLIENT>>> TERMINATE"));
  }

客户端:

    // the thread that will be communicating with the server
    public class ServerConnection extends Thread 
    {
        // the I/O streams that will be receiving/sending data from/to the
        // server
        private ObjectOutputStream output;
        private ObjectInputStream input;

        private Socket client;

        @Override
        public void run() 
        {
            try 
            {
                // Step 1: Create a Socket to make connection
                connectToServer();

                // Step 2: Get the input and output streams
                getStreams();

                // Step 3: Process connection
                processConnection();

                // Step 4: Close connection
                //closeConnection();
            } 
            catch (IOException e) 
            {
                Log.e("CONNECTION", e.getMessage());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        private void connectToServer() throws IOException {
            addMessage("Attempting connection\n");
            client = new Socket(##IP Address##, 5001);
            addMessage("Connected to: " + client.getInetAddress().getHostName());
        }

        private void getStreams() throws IOException 
        {
            output = new ObjectOutputStream(client.getOutputStream());
            output.flush();
            input = new ObjectInputStream(client.getInputStream());
            connection.sendData("You got the streams");
            addMessage("Got I/O streams");
        }



        private void processXML(String m) throws Exception
        {

               addMessage(m);
        }

        public void processConnection() throws Exception 
        {   

                    do 
                    {
                        try 
                        {
                            message = (String) input.readObject();
                            addMessage(message);
                            processXML(message);
                        } 
                        catch (ClassNotFoundException classNotFoundException) 
                        {
                            addMessage("ERROR: Unknown object type received");
                        } catch (OptionalDataException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    while (!message.equals("SERVER>>> TERMINATE"));         
        }

        private void sendData(String message) {
            try {
                output.writeObject(message);
                output.flush();
                addMessage("CLIENT>>>" + message);
            } catch (IOException ioException) {
                addMessage("ERROR: Error writing object");
            }
        }

        private void closeConnection() throws IOException {
            addMessage("Closing connection");
            output.close();
            input.close();
            client.close();
        }

    }

清单:

  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="example02"
 android:versionCode="1"
 android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="LoginActivity"
        android:label="@string/app_name" >
    </activity>
    <activity
        android:name="AddTutor"
        android:label="@string/title_activity_add_tutor" >
    </activity>
    <activity
        android:name="InsertTutor"
        android:label="@string/title_activity_insert_tutor" >
    </activity>
  </application>
 </manifest>

我在两个Android活动中都运行完全相同的客户端代码,但是第二个活动却从未得到我的流。 请告诉我我哪里出错了,因为我沮丧地拔头发。

1 个答案:

答案 0 :(得分:0)

我很傻。我忘了在我的清单中添加互联网权限。对于有这个问题的人,我已经解决了。