这是我的消息传递程序的代码。它由三个jframe文件,一个服务器文件和两个客户端文件组成。到目前为止,代码实现了一半的要求,两个客户端都能够发送消息,服务器接收并显示它。但是我对如何扩展代码感到困惑,以便客户端A将接收客户端B发送的消息,反之亦然。
服务器代码是:
package Chats;
import java.io.*;
import java.net.*;
import java.util.*;
public class Chat_Server extends javax.swing.JFrame
{
static ServerSocket ss;
public Chat_Server()
{
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
Msg_Area = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Msg_Area.setColumns(20);
Msg_Area.setRows(5);
jScrollPane1.setViewportView(Msg_Area);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(36, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(38, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Chat_Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Chat_Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Chat_Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Chat_Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new Chat_Server().setVisible(true);
}
});
//String msgin = "";
try
{
ss = new ServerSocket(1201); // Server starts at 1201 port number
ArrayList<Socket> clients = new ArrayList<Socket>();
while(true)
{
Socket s = ss.accept(); // Now server will accept the connections.
clients.add(s);
new Thread(new Runnable()
{
//@Override
public void run()
{
try
{
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
String msgin = "";
while (!msgin.equals("exit"))
{
msgin = din.readUTF();
Msg_Area.setText(Msg_Area.getText().trim() + "\n Client 1: \t" + msgin); // Displaying the message from client
}
din.close();
dout.close();
s.close();
clients.remove(s);
}
catch (Exception e)
{
//Exception Code Here
}
}
}).start();
}
}
catch(Exception e)
{
}
}
// Variables declaration - do not modify
private static javax.swing.JTextArea Msg_Area;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
两个客户都有代码:
package Chats;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
public class Chat_Client extends javax.swing.JFrame
{
static Socket s;
static DataInputStream din;
static DataOutputStream dout;
public Chat_Client()
{
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
Msg_Text = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
Msg_Area = new javax.swing.JTextArea();
Msg_Send = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Msg_Text.setText("jTextField1");
Msg_Area.setColumns(20);
Msg_Area.setRows(5);
jScrollPane1.setViewportView(Msg_Area);
Msg_Send.setText("jButton1");
Msg_Send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Msg_SendActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(Msg_Text, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addComponent(Msg_Send)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Msg_Text, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Msg_Send))
.addGap(23, 23, 23))
);
pack();
}// </editor-fold>
private void Msg_SendActionPerformed(java.awt.event.ActionEvent evt) {
try
{
String msgout = "";
msgout = Msg_Text.getText().trim();
dout.writeUTF(msgout);
}
catch (Exception e)
{
//handle exceptions here.
}
}
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Chat_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Chat_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Chat_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Chat_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new Chat_Client().setVisible(true);
}
});
try
{
s = new Socket ("127.0.0.1", 1201); // Here the ip ddress is local address.
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
String msgin = "";
while (!msgin.equals("exit"))
{
msgin = din.readUTF();
Msg_Area.setText(Msg_Area.getText().trim() + "\n Client 2: \t" + msgin);
}
}
catch(Exception e)
{
//Exception Code
}
}
// Variables declaration - do not modify
private static javax.swing.JTextArea Msg_Area;
private javax.swing.JButton Msg_Send;
private javax.swing.JTextField Msg_Text;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
所有代码都使用相同的&#34; 1201&#34;端口和两个客户端使用localhost IP地址连接。我希望它工作,以便我可以运行服务器,然后运行两个客户端,并能够在它们之间发送消息。