- 论坛徽章:
- 0
|
刚学习JAVA不久
自己学着写了个SOCKET 聊天程序
想实现的功能:
打开服务器端,能接受多客户的进入,每一个动作都是定写进SWING 组件中JTextArea
只要求服务器端能够记录下客户的聊天记录.
但是出了问题:
每连接一个客户,都会新建一个服务器端的SWING;
代码如下
服务器端:
//ChatServer.java
import java.net.*;
import java.io.*;
public class ChatServer implements Runnable
{
Socket socket;
BufferedReader in;
PrintWriter out;
ChatServerFrame csf = new ChatServerFrame(); //做为服务器端的界面
public ChatServer()
{
int PORT = 8505; //端口号
try{
ServerSocket s = new ServerSocket(PORT);
csf.setLog("Server is startting..." ;
csf.setLog("Listening on port : " + PORT );
while(true){
Socket socket = s.accept(); //
this.getIP(socket);
ChatServer server = new ChatServer(socket);
Thread thread = new Thread(server);//为每一个客户打开一个线程
thread.start(); //线程开始
}
}catch(Exception e){
csf.setLog("Server error : " ;
csf.setLog(e.toString());
}
}
ChatServer(Socket socket)
{
this.socket = socket;
}
public void getIP(Socket skt)
{
InetAddress ia = skt.getInetAddress();
String ip = ((ia.toString()).split("/" )[1].toString();
csf.setLog("Connected : " + ip);
}
public void run(){
try{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
while(true){
String str = in.readLine();
csf.setLog(str);
}
}catch(Exception e){ csf.setLog(e.toString());}
finally{
csf.setLog("Disconnect! IP = " + getIP(socket));
try{
socket.close();
}catch(IOException e){
csf.setLog("Error : " ;
csf.setLog(e.toString());
}
}
}
public static void main(String[] args)
{
ChatServer cs = new ChatServer();
}
}
ChatServerFrame.java
import java.awt.*;
import javax.swing.*;
public class ChatServerFrame extends JFrame
{
public JTextArea stateJTA;
JScrollPane stateJSP;
JPanel stateJP;
JList nameJL;
JScrollPane nameJSP;
JPanel nameJP;
JButton startJB = new JButton(" Start " ;
JButton saveJB = new JButton("Save Log" ;
JButton exitJB = new JButton(" Exit " ;
JButton kickJB = new JButton(" Kick " ;
JPanel actJP;
JPanel rightJP;
String[] nameList = {"219.217.42.181","219.217.42.182","219.217.42.183","219.217.42.184","219.217.42.185","1","2","3","4","5","6","7","8"};
public ChatServerFrame()
{
//GridBagLayout gridbag = new GridBagLayout();
//GridBagConstraints gbc = new GridBagConstraints();
stateJTA = new JTextArea(25,35);
stateJTA.setLineWrap(true);
stateJTA.setEditable(false);
stateJSP = new JScrollPane(stateJTA);
stateJP = new JPanel(new FlowLayout(FlowLayout.CENTER));
nameJL = new JList(nameList);
nameJSP = new JScrollPane(nameJL);
nameJP = new JPanel(new FlowLayout(FlowLayout.CENTER));
rightJP = new JPanel(new GridLayout(2,1));
actJP = new JPanel(new GridLayout(4,1,10,10));
nameJSP.setPreferredSize(new Dimension(140, 200));
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(stateJP);
c.add(rightJP);
stateJP.add(stateJSP);
rightJP.add(nameJP);
rightJP.add(actJP);
nameJP.add(nameJSP);
actJP.add(startJB);
actJP.add(saveJB);
actJP.add(exitJB);
actJP.add(kickJB);
this.setSize(600,550);
this.setTitle("Server_MyChat..." ;
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setLog(String str)
{
stateJTA.append(str + "\n" ;
}
//public static void main(String[] args)
//{
// ChatServerFrame csf = new ChatServerFrame();
//}
}
客户端:
package chat.client;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ChatClientMain extends JFrame implements ActionListener
{
JLabel numJL;
JTextArea contentJTA;
JTextArea wordJTA;
JScrollPane contentJSP;
JScrollPane wordJSP;
JButton sendJB;
JButton exitJB;
JPanel midJP;
JPanel downJP;
JPanel downrightJP;
String username;
Socket s;
BufferedReader br;
OutputStream os;
OutputStreamWriter osw;
PrintWriter pw;
public ChatClientMain()
{
numJL = new JLabel();
contentJTA = new JTextArea(15,30);
contentJSP = new JScrollPane(contentJTA);
wordJTA = new JTextArea(3,25);
wordJSP = new JScrollPane(wordJTA);
sendJB = new JButton("Send");
exitJB = new JButton("Exit");
midJP = new JPanel(new FlowLayout(FlowLayout.CENTER));
downJP = new JPanel(new FlowLayout());
downrightJP = new JPanel(new GridLayout(2,1));
Container c = getContentPane();
c.add(numJL, BorderLayout.NORTH);
c.add(midJP, BorderLayout.CENTER);
c.add(downJP, BorderLayout.SOUTH);
midJP.add(contentJSP);
downJP.add(wordJSP, BorderLayout.WEST);
downJP.add(downrightJP, BorderLayout.EAST);
contentJTA.setLineWrap(true);
contentJTA.setEditable(false);
wordJTA.setLineWrap(true);
wordJTA.grabFocus();
downrightJP.add(sendJB);
downrightJP.add(exitJB);
sendJB.addActionListener(this);
exitJB.addActionListener(this);
this.setTitle("Chatting...");
this.setSize(380,420);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int port = 8505;
try{
s = new Socket("219.217.42.181",port);
os = s.getOutputStream();
osw = new OutputStreamWriter(os);
pw = new PrintWriter(osw);
InputStreamReader isr = new InputStreamReader(s.getInputStream());
BufferedReader br = new BufferedReader(isr);
}catch(IOException e){
contentJTA.setText(e.toString());
// System.out.println(e);
}catch(Exception ee){
contentJTA.setText(ee.toString());
// System.out.println(ee);
}
// Thread ThreadReader = new Thread(this);
// ThreadReader.start();
}
//public void run()
//{
// while(true){
// try{
// contentJTA.append(username + br.readLine());
// }catch(Exception exo){}
// }
//}
public void setName(String name)
{
username = name;
this.numJL.setText("the chatter now is:" + username);
}
private void nullError(String errorInfo,String errorType)
{
JOptionPane.showMessageDialog(this,errorInfo,errorType,JOptionPane.INFORMATION_MESSAGE);
}
public void actionPerformed(ActionEvent e)
{
String myWord = wordJTA.getText().trim();
if(e.getSource() == sendJB)
{
if(myWord.equals(""))
{
this.nullError("The Message Connot Be Null!","Input Error");
wordJTA.grabFocus();
}else{
contentJTA.append(username + ":" + myWord + "\n");
wordJTA.setText(null);
wordJTA.grabFocus();
String mymsg = this.username + "::" +myWord;
try{
pw.println(mymsg);
pw.flush();
}catch(Exception ec){
wordJTA.setText("Message Sending Failed!");
}
wordJTA.grabFocus();
}
}
if(e.getSource() == exitJB)
{
System.exit(0);
}
}
public static void main(String[] args)
{
ChatClientMain ccm = new ChatClientMain();
}
} |
|