小聊天程序,访问文件之间的变量

时间:2016-11-30 21:54:00

标签: java

目前我正在创建一个简单的聊天程序,允许您在服务器之间进行通信。我在访问username变量时遇到问题,因为它在另一个文件中的一个文件中使用。用户将输入他的名字,这是在ChatGUI文件中完成的,然后当他进入聊天室时,会创建一个EchoFrame,它位于EchoFrame文件中。同样在EchoFrame文件中,我想将用户名附加到用户消息,并在他们连接到聊天室以及何时离开聊天室时进行通知。我希望我能清楚地解释我的问题,所需的任何其他信息请告诉我!

EchoFrame

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
xmlns:local="clr-namespace:ViewModels;assembly=AsyncFS"
xmlns:fsxaml="http://github.com/fsprojects/FsXaml"
Title="MVVM and XAML Type provider" Height="200" Width="400">
<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
    </Grid.RowDefinitions>
    <WindowsFormsHost Child="{Binding LineChart}" />
</Grid>

ChatGUI

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class EchoFrame extends Frame{

    EchoPanel ep;
    Button sendMessage;

    public EchoFrame(){

        setSize(500,500);
        setTitle("Echo Client");
        addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent we){
                System.exit(0);
            }
        });

        ep = new EchoPanel();
        add(ep, BorderLayout.CENTER);




        setVisible(true);
    }

    public static void main(String[] args){

        EchoFrame ef = new EchoFrame();

    }
}


class EchoPanel extends Panel implements ActionListener, Runnable{

    TextField tf;
    TextArea ta;
    Button connect, disconnect;
    Socket s;
    BufferedReader br;
    PrintWriter pw;
    Thread t;
    String fromServer;
    String username;


    public EchoPanel(){

        setLayout(new BorderLayout());
        tf = new TextField();
        tf.setEditable(false);
        tf.addActionListener(this);
        add(tf, BorderLayout.NORTH);
        ta = new TextArea();
        ta.setEditable(false);
        add(ta, BorderLayout.CENTER);
        Panel buttonPanel = new Panel();
        connect = new Button("Connect");
        connect.addActionListener(this);
        buttonPanel.add(connect);
        disconnect = new Button("Disconnect");
        disconnect.setEnabled(false);
        disconnect.addActionListener(this);
        buttonPanel.add(disconnect);
        add(buttonPanel, BorderLayout.SOUTH);



    }

    public void actionPerformed(ActionEvent ae){

        if(ae.getSource() == connect){
            try{
                s = new Socket("127.0.0.1", 8189);
                ta.append(username + " has entered the chat room. \n");
                br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                pw = new PrintWriter(s.getOutputStream(), true);
            }catch(UnknownHostException uhe){
                System.out.println(uhe.getMessage());
            }catch(IOException ioe){
                System.out.println(ioe.getMessage());
            }

            t = new Thread(this);
            t.start();
            tf.setEditable(true);
            connect.setEnabled(false);
            disconnect.setEnabled(true);
        }else if(ae.getSource() == disconnect){
            try{
                pw.close();
                br.close();
                s.close();
            }catch(IOException ioe){
                System.out.println(ioe.getMessage());
            }
            t = null;
            ta.append(username + " has disconnected from chat room. \n");
            tf.setEditable(false);
            connect.setEnabled(true);
            disconnect.setEnabled(false);
        }else if(ae.getSource() == tf){
            String fromTf = tf.getText();
            pw.println(fromTf);
            tf.setText("");

        }else{

                //additional events
        }
    }

    public void run (){
        fromServer = "";
        try{
            while((fromServer = br.readLine()) != null){

                    ta.append(username + ":" + fromServer + "\n");
            }   
        }catch(IOException ioe){
            System.out.println(ioe.getMessage());
        }
    }

}

聊天服务器

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;




public class ChatGUI extends JFrame {

    private int currentCard = 1;
    private JPanel cardPanel;
    private CardLayout cl;
    JTextField usernameField;
    String username;

    public ChatGUI() {

        setTitle("Chat Program");
        setSize(500, 120);
        cardPanel = new JPanel();

        cl = new CardLayout();
        cardPanel.setLayout(cl);

        JPanel chooseUsername = new JPanel();
        JLabel usernameLabel = new JLabel("Please enter your username:");

        chooseUsername.add(usernameLabel);
        cardPanel.add(chooseUsername, "Log in");

        usernameField = new JTextField(15);


        usernameField.setEditable(true);
        add(usernameField, BorderLayout.CENTER);


        JPanel buttonPanel = new JPanel();
        JButton logInBtn = new JButton("Enter Chat Room");

        buttonPanel.add(logInBtn);



        logInBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                currentCard = 2;
                cl.show(cardPanel, "" + (currentCard));

                username = usernameField.getText();  //gets username
                EchoFrame ef = new EchoFrame();    //creates message room

            }
        });


        getContentPane().add(cardPanel, BorderLayout.NORTH);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    }
    public static void main(String[] args) {
        ChatGUI cl = new ChatGUI();
        cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cl.setVisible(true);
    }
}

聊天处理程序

import java.io.*;
import java.net.*;
import java.util.*;

public class ChatServer{
    Socket s;
    ArrayList <ChatHandler>handlers;
    public ChatServer(){
        try{
            ServerSocket ss = new ServerSocket(8189);
            handlers = new ArrayList<ChatHandler>();
            for(;;){
                s = ss.accept();
                new ChatHandler(s, handlers).start();
            }
        }catch(IOException ioe){
            System.out.println(ioe.getMessage());
        }
    }
    public static void main(String[] args){
        ChatServer tes = new ChatServer(); 
    }
}

2 个答案:

答案 0 :(得分:1)

userName设为静态,然后通过ChatUI.userName访问它。实际上,userName不应该在ChatUI中。或者,更重要的选择是获取MySQL,设置数据库,并通过JDBC连接到它,如果您将拥有多个用户。

您也可以尝试按照以下示例进行操作:Simple Client And Server Chat ProgramCreating a simple Chat Client/Server Solution。它们涵盖了关键主题,例如多线程。

答案 1 :(得分:0)

我认为您应该有一个服务器程序和一个客户端程序,因此您需要发送给每个客户端的所有变量都可以进入服务器。

当客户端连接到服务器时,您将该客户端(用户名,ipadress等)添加到已连接客户端列表中,并创建一个新线程来侦听/发送到该客户端。然后从服务器你可以发送给所有用户(线程)用户名和他写的如果你有一个函数sendToAll(idThreadSender,threadX.text)或你可以发送到线程(threadX,threadY.text)我认为你有一个坏结构,就是这样。

希望我帮忙。