0

我正在用 java 中的套接字编写客户端服务器应用程序。客户端和服务器都位于我的计算机上。目标是将消息从客户端发送到服务器。我认为我的套接字没问题,但是我获取消息的方式有问题。也由于某种原因,当我单击连接或启动服务器时,服务器和客户端有时会“卡住”。

这是客户端代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Time;

import javax.swing.*;

public class Client extends JFrame{
private int connected = 0;
private JTextArea txt;
private JTextField mText;
private JButton sendMessage;
private JScrollPane scroll;
    private JButton connect;
private JButton disconnect;
    private Socket socket;
    private ObjectInputStream input;
    private ObjectOutputStream output;
    private PrintWriter out;
public Client(){
    setLayout(null);

    txt = new JTextArea();
    scroll = new JScrollPane(txt);
    scroll.setBounds(25,10,325,200);
    add(scroll);


    mText = new JTextField();
    mText.setBounds(25,220,250,30);
    add(mText);

    sendMessage=new JButton("Send");
    sendMessage.setBounds(280,220,70,30);   
    add(sendMessage);

    connect= new JButton("Connect");
    connect.setBounds(25,260,100,30);
    add(connect);

    disconnect = new JButton("Disconnect");
    disconnect.setBounds(135,260,100,30);
    add(disconnect);
  //events stuff
       eventHandler handler = new eventHandler();
       sendMessage.addActionListener(handler);
       connect.addActionListener(handler);
       disconnect.addActionListener(handler);
   }
public class eventHandler implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==sendMessage){
            sendMessage();
        }
        else
            if(e.getSource()==connect){
            if(connected==0){
            try{
             connect();
             connected = 1;
             }catch(Exception e1){
                 e1.printStackTrace();
                 System.out.print(e1);
             }
            }else
                printOnScreen("you are already connected...");
          }
        else
            if(e.getSource()==disconnect){
                if(connected==1){
                 try{
                    disconnect();
                    connected = 0;
                 }catch(Exception e1){
                     e1.printStackTrace();
                     System.out.print(e1);
                 }
                 }else{printOnScreen("you are not connected");} 
             }
  }
}


public void printOnScreen(String m){
    txt.append("\n"+m);
}

public void sendMessage(){
    String message = txt.getText();
    out.print(message);
}
public void connect() throws UnknownHostException, IOException{
    socket=new Socket("localhost",6789);
    input = new ObjectInputStream(socket.getInputStream());
    output= new ObjectOutputStream(socket.getOutputStream());
    out = new PrintWriter(socket.getOutputStream(),true);
    out.print("client connecting");
    out.flush();
}
public void disconnect() throws IOException{
    out.print("Client disconnecting");
    out.flush();
    out.close();
    input.close();
    output.close();
    socket.close();
}

public static void main(String[]args){
    Client cFrame = new Client();
    cFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    cFrame.setSize(385,350);
    cFrame.setTitle("             ---___Client1___---");
    cFrame.setVisible(true);
}

}

和服务器代码:

import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.EventHandler;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.*;
import javax.swing.*;
public class Server extends JFrame {
private int running =0;

private JPanel showInformation;
private JButton start;
private JButton stop;
private JTextArea infoArea;
private JScrollPane scroll;

private ServerSocket server;
private Socket client;   

private ObjectOutputStream output;
private ObjectInputStream input;

private PrintWriter out;

public Server(){
   //setting looks of Frame
   setLayout(null);
   showInformation=new JPanel();
   start = new JButton("Start Server");
   stop=new JButton("Stop Server");
   infoArea= new JTextArea(20,27);
   infoArea.setEnabled(false);
   infoArea.setEditable(false);
   scroll = new JScrollPane(infoArea);
   scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
   scroll.setBounds(25,10,325,200);
   scroll.setEnabled(true);
   add(scroll);

   showInformation.setSize(300, 200);
   showInformation.setBounds(25,5,325,200);
   add(showInformation);
   infoArea.setLineWrap(true);
   start.setBounds(25,225,150,50);
   stop.setBounds(200,225,150,50);

   add(start);
   add(stop);     
   //events stuff
   eventHandler handler = new eventHandler();
   start.addActionListener(handler);
   stop.addActionListener(handler);

   //sockets 
}

public void printOnScreen(String m){
    infoArea.append("\n"+m);
}

public class eventHandler implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==start){
              if(running==1)
                  printOnScreen("Server Already Running !!!");
              else
              {
                  try{
                       startServer();
                  }catch(Exception e1){
                      e1.printStackTrace();
                      System.out.print(e1);
                  }
                  running=1;

              }
           }
        else 
          if(e.getSource()==stop){
              if(running==0)
                  printOnScreen("Server Not Running !!!");
              else
              {
                  try{
                      stopServer();
                  }catch(Exception e1){
                      e1.printStackTrace();
                      System.out.print(e1);
                  }
                  running=0;
             }
    }

}
}

public void startServer() throws IOException{
    server = new ServerSocket(6789);
    running=1;
    Listener ls = new  Listener();
    ls.run();
    client =  server.accept();
    input = new ObjectInputStream(client.getInputStream());
    output = new ObjectOutputStream(client.getOutputStream());
    output.flush();
    out = new PrintWriter(client.getOutputStream(),true);
    out.flush();
    printOnScreen("Server Started !!!");
    printOnScreen("waiting for connection...");
}

public void stopServer() throws IOException{
  output.writeObject("Server Stoped");
  output.flush();
  input.close();
  output.close();
  client.close();
  server.close();
  printOnScreen("Server Stopped");
}


public void getMessage() throws ClassNotFoundException, IOException{
try{
    String message = (String)input.readObject();
    printOnScreen("client: "+message);
}catch(Exception e){
    e.printStackTrace();
}

}

class Listener extends Thread{
    public Listener(){

    }
    public void run(){
        try {
            client = server.accept();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            System.out.print(e1);
        }
        while(running==1){
            try {
                Thread.sleep(4000);
                getMessage();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                System.out.print(e);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.print(e);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

public static void main(String[]args){
   Server s = new Server();
   s.setDefaultCloseOperation(EXIT_ON_CLOSE);
   s.setSize(385, 350);
   s.setVisible(true);
   s.setTitle("      ----Server----");
   s.setTitle("Server Manager");
 }

}

这是错误代码:

 java.lang.NullPointerException
at Server.getMessage(Server.java:129)
at Server$Listener.run(Server.java:152)
at Server.startServer(Server.java:105)
at Server$eventHandler.actionPerformed(Server.java:73)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
4

0 回答 0