在JAVA中创建服务器端聊天程序时出错?

时间:2015-09-01 13:12:40

标签: java eclipse netbeans

所以,我正在尝试创建一个Client Server聊天程序。因为,我没有外部服务器,因此我的客户端和服务器将托管在我的计算机中。现在,我正在关注在线教程并创建了聊天程序的服务器端,但是当我测试程序的服务器端时,我得到了一个错误。当我创建服务器套接字时,如果我正在使用我的计算机,我应该放入什么端口号。我用了一个随机数,我得到以下错误: - 有人可以帮我修复错误或建议我该怎么办?感谢

enter image description here

这是我的服务器类: -

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.io.*;
import java.awt.*;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;




public class Server extends JFrame {

    private JTextField usertext;
    private JTextArea  chatwindow;
    private ObjectOutputStream output;
    private ObjectInputStream input;

    private ServerSocket server;
    private Socket connection;


    public Server()
    {
        super("Missy's Instant Messenger");//This sets the title of the messenger window
        usertext = new JTextField(); //this is for creating the textfield where the user will enter data
        usertext.setEditable(false);//this is set to false such that the user can only send message if he is connected to someone 
        usertext.addActionListener( //this activity is for sending the message when the user clicks on enter
                new ActionListener(){
            public void actionPerformed(ActionEvent event){
                sendMessage(event.getActionCommand());
                usertext.setText(" ");

            }

        /*  private void sendMessage(String string) {
                // TODO Auto-generated method stub

            }*/
        });

         add(usertext,BorderLayout.NORTH); 
         chatwindow = new JTextArea();
         add(new JScrollPane(chatwindow));
         setSize(500,500);




    }


   public void startrunning(){

       try {
        server = new ServerSocket(6800,100);
        //6789 is the port number and 100 is the number of people that can wait in the queue to connect to the server

        while(true)
        {
            try{
                waitforConnection();//this is to connect to the server
                setupStreams();//setting up the input and output streams to send and receive messages
                whilechatting();//this is allow to send messages using the input and output streams



            }catch (Exception e)
            {
                showMessage("Connection has ended");//this will be displayed when the connection is ended by the server

            }finally{
                closecrap(); //close all the streams and sockets 
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

   }

   private void waitforConnection() throws IOException
   {
       showMessage("waiting for someone to connect.....");
       connection = server.accept(); //this will connect the server and the client
       showMessage("Now connected to "+connection.getInetAddress().getHostName());

   }

   private void setupStreams() throws IOException
   {
       output = new ObjectOutputStream(connection.getOutputStream());
       output.flush();

       input = new ObjectInputStream(connection.getInputStream());
       showMessage("Your streams are now set up......");
   }


   private void whilechatting() throws IOException
   {
       String message = "You are now connected";
       sendMessage(message);
       abletotype(true);

       do{

           try{
               message = (String)input.readObject();
               showMessage("\n" +message);

           }catch(ClassNotFoundException e)
           {
               showMessage("wtf is that");
           }




       }while(!message.equals("CLIENT END"));

   }

   private void showMessage(final String a)

   {
       SwingUtilities.invokeLater(

               new Runnable(){

                   public void run(){
                       chatwindow.append(a);
                   }
               }

               );
     //  System.out.println(a);
   }

   public void closecrap()
   {
       showMessage("\n Connections closing .....");
       abletotype(false);
       try{
           output.close();
           input.close();
           connection.close();

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

   public void sendMessage(String message)
   {
       try{
           output.writeObject("SERVER - "+message);//this is where you put the message in the output stream
           output.flush(); //flush out the junk if there is any left
           showMessage("\nSERVER -"+message); //show Message in the chat window

       }catch(Exception e)
       {
           chatwindow.append("\n ERROR sending the message dude");
       }
   }



   private void abletotype(final Boolean t)
   {
       SwingUtilities.invokeLater(

               new Runnable(){

                   public void run(){
                       usertext.setEditable(t);
                   }
               }

               );
   }
}

Servertest课程: -

 import javax.swing.*;
public class ServerTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Server st = new Server();
        st.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        st.startrunning();


    }

}

参考文献: - ThenewBoston.com

1 个答案:

答案 0 :(得分:0)

我将总结一些评论中所说的内容,并添加我自己的想法。

首先,该端口可能已在使用中。它可能没有被您所说的程序使用,但是其他一些程序正在使用它或保留它。据我所知,端口100没有正式使用,所以很可能只是你机器上安装的另一个程序。同样来自评论,你似乎已经通过交换到另一个端口来解决这个问题。

Connection.close()应该可以正常关闭连接。有关详细信息,请查看此链接:How can I close the socket in a proper way?

就您最近的评论而言 - 如果程序正在运行但UI未显示,则您可能会遇到与您发布的问题无关的代码的另一个问题。我可能会建议尝试自己调试它,因为服务器在没有JVM_BIND错误的情况下启动,看看你提出了什么。