使用JDBC的群聊服务器

时间:2018-05-31 13:36:57

标签: java mysql jdbc server client

我知道那里有无数的聊天服务器,但我似乎无法在我的代码中应用解决方案。 我的代码工作的方式是我启动一个服务器,我可以连接任意数量的客户端,这个服务器都可以一起通信。除了最重要的部分,我一切都在工作。我似乎无法让客户端显示彼此的消息。我尝试使用JDBC,但每次添加时都会返回太多错误。

public class Client {

private static final String host = "localhost";
private static final int portNumber = 4466;

private String userName;
private String serverHost;
private int serverPort;
private Scanner userInputScanner;
static JButton enterButton;
public static JTextArea output;
public static JTextField input;
static JFrame frame;
static JPanel panel;
public static String testString = "test";

public static void main(String[] args){
    String readName = null;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please input username:");
    while(readName == null || readName.trim().equals("")){
        readName = scan.nextLine();
        if(readName.trim().equals("")){
            System.out.println("Invalid. Please enter again:");
        }
    }

    Client client = new Client(readName, host, portNumber);
    client.startClient(scan);
}


private void startClient(Scanner scan){
    try{

        Socket socket = new Socket(serverHost, serverPort);
        Thread.sleep(1000); // waiting for network communicating.

        ServerThread serverThread = new ServerThread(socket, userName);
        Thread serverAccessThread = new Thread(serverThread);
        serverAccessThread.start();
        while(serverAccessThread.isAlive()){
            if(scan.hasNextLine()){
                serverThread.addNextMessage(scan.nextLine());
            }

        }
    }catch(IOException ex){
        System.err.println("Fatal Connection error!");
        ex.printStackTrace();
    }catch(InterruptedException ex){
        System.out.println("Interrupted");
    }
}

private Client(String userName, String host, int portNumber){
    this.userName = userName;
    this.serverHost = host;
    this.serverPort = portNumber;

}
}



public class ChatServer {

private static final int portNumber = 4466;

private int serverPort;
private List<ClientThread> clients; 

public static void main(String[] args){
    ChatServer server = new ChatServer(portNumber);
    server.startServer();
}

public ChatServer(int portNumber){
    this.serverPort = portNumber;

            }


public List<ClientThread> getClients(){
    return clients;
}

private void startServer(){
    clients = new ArrayList<ClientThread>();
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(serverPort);
        acceptClients(serverSocket);
    } catch (IOException e){
        System.err.println("Could not listen on port: "+serverPort);
        System.exit(1);
    }
}

private void acceptClients(ServerSocket serverSocket){

    final JFrame frame = new JFrame("Server Window");
    frame.setSize(600, 400);
    frame.getContentPane().setBackground( Color.BLACK );
    //--------------------------------------//
    //Display
    JPanel display = new JPanel();
    JTextArea editArea2 = new JTextArea(22,52);
    display.add(editArea2);
    frame.add(display);
    display.setBackground(Color.BLACK);


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           
        frame.setLocation(2000, 100);
        frame.setBackground(Color.BLACK);
        frame.setVisible(true);

    editArea2.append("server starts port = " + serverSocket.getLocalSocketAddress() + "\n");
    while(true){
        try{
            Socket socket = serverSocket.accept();
            editArea2.append("accepts : " + socket.getRemoteSocketAddress() + "\n");
            ClientThread client = new ClientThread(this, socket);
            Thread thread = new Thread(client);
            thread.start();
            clients.add(client);
        } catch (IOException ex){
            editArea2.append("Accept failed on : "+serverPort);
        }
    }
}   

}


public class ChatServer {

private static final int portNumber = 4466;

private int serverPort;
private List<ClientThread> clients; 

public static void main(String[] args){
    ChatServer server = new ChatServer(portNumber);
    server.startServer();
}

public ChatServer(int portNumber){
    this.serverPort = portNumber;

            }


public List<ClientThread> getClients(){
    return clients;
}

private void startServer(){
    clients = new ArrayList<ClientThread>();
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(serverPort);
        acceptClients(serverSocket);
    } catch (IOException e){
        System.err.println("Could not listen on port: "+serverPort);
        System.exit(1);
    }
}

private void acceptClients(ServerSocket serverSocket){

    final JFrame frame = new JFrame("Server Window");
    frame.setSize(600, 400);
    frame.getContentPane().setBackground( Color.BLACK );
    //--------------------------------------//
    //Display
    JPanel display = new JPanel();
    JTextArea editArea2 = new JTextArea(22,52);
    display.add(editArea2);
    frame.add(display);
    display.setBackground(Color.BLACK);


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           
        frame.setLocation(2000, 100);
        frame.setBackground(Color.BLACK);
        frame.setVisible(true);

    editArea2.append("server starts port = " + serverSocket.getLocalSocketAddress() + "\n");
    while(true){
        try{
            Socket socket = serverSocket.accept();
            editArea2.append("accepts : " + socket.getRemoteSocketAddress() + "\n");
            ClientThread client = new ClientThread(this, socket);
            Thread thread = new Thread(client);
            thread.start();
            clients.add(client);
        } catch (IOException ex){
            editArea2.append("Accept failed on : "+serverPort);
        }
    }
}   

}

public class ServerThread implements Runnable {
private Socket socket;
private String userName;
private final LinkedList<String> messagesToSend;
private boolean hasMessages = false;

private static String ENTER = "Enter";
static JButton enterButton;
public static JTextArea output;
public static JTextField input;
static JFrame frame;
static JPanel panel, imagePanel;
public static String testString = "test";
String userWord = "";

public JTextField text;

public BufferedReader in ;
public PrintWriter out;
public OutputStream outputStream;

public void addNextMessage(String message){
    synchronized (messagesToSend){
        hasMessages = true;
        messagesToSend.push(message);
    }
}


@Override
public void run(){
    output.append("Welcome to the chat room :" + userName + "\n");

    try{

        //This is where i am going wrong. I can't get the messages to pass the input stream correctly
        OutputStream os = socket.getOutputStream();
        PrintWriter serverOut = new PrintWriter(socket.getOutputStream(), true);
        text= new JTextField();
        String str = text.getText();

        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        str = br.readLine();
        serverOut.println(str);      

        while(!socket.isClosed()){
            if(br.ready() == true){
                {

                    serverOut.println(str);
                    System.out.println(str);
                }
            }
            if(hasMessages)
            {
                String nextSend = "";
                synchronized(messagesToSend){
                    nextSend = messagesToSend.pop();
                    hasMessages = !messagesToSend.isEmpty();
                }
                output.append(userName + " > " + nextSend);
            }
        }
    }
    catch(IOException ex){
        ex.printStackTrace();
    }

}
//creating my JPanel
public ServerThread(Socket socket, String userName){
    this.socket = socket;
    this.userName = userName;
    messagesToSend = new LinkedList<String>();



    frame = new JFrame("Chat Server "+ userName);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setSize(600, 400);   
    panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.setOpaque(true);
    ButtonListener buttonListener = new ButtonListener();
    output = new JTextArea(15, 40);
    output.setWrapStyleWord(true);
    output.setEditable(false);
    JScrollPane scroller = new JScrollPane(output);
    scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    JPanel inputpanel = new JPanel();
    inputpanel.setLayout(new FlowLayout());
    input = new JTextField(20);
    enterButton = new JButton("Send");
    imagePanel = new JPanel();
    imagePanel.setSize(20,20);
    imagePanel.setVisible(true);        
    enterButton.setActionCommand(ENTER);
    enterButton.addActionListener(buttonListener);
    input.setActionCommand(ENTER);
    input.addActionListener(buttonListener);
    DefaultCaret caret = (DefaultCaret) output.getCaret();
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    panel.add(scroller);
    inputpanel.add(imagePanel);
    inputpanel.add(input);
    inputpanel.add(enterButton);
    panel.add(inputpanel);
    frame.getContentPane().add(BorderLayout.CENTER, panel);
    frame.setLocationByPlatform(true);
    frame.setLocationRelativeTo(null);
    frame.pack();
    frame.setVisible(true);
    frame.setResizable(false);
    input.requestFocus();

    final JToolBar toolBar = new JToolBar();

    JButton upload = new JButton("Upload");
    toolBar.add(button);
    toolBar.add(upload);
    frame.getContentPane().add(toolBar, BorderLayout.SOUTH);



 upload.addActionListener(new ActionListener() {

       @Override
       public void actionPerformed(ActionEvent e) {
        JFileChooser fc = new JFileChooser();
        fc.showOpenDialog(null);
        File f = fc.getSelectedFile();
        String filename = f.getAbsolutePath();


         try {
             File file = new File(filename);

             BufferedImage image = ImageIO.read(file);
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ImageIO.write(image, "jpg", baos);         




            } catch (IOException e1) {
             // TODO Auto-generated catch block
             e1.printStackTrace();
            }         
           } 

          });
}

public static class ButtonListener implements ActionListener
{

    public void actionPerformed(final ActionEvent ev)
    {
        if (!input.getText().trim().equals(""))
        {
            String cmd = ev.getActionCommand();
            if (ENTER.equals(cmd))
            {
                output.append(input.getText());
                input.getText().trim().equals(testString);                                  
                output.append("\n");                
            }
        }
        input.setText("");
        input.requestFocus();
    }
}
}

0 个答案:

没有答案