我有一个多线程服务器和2个连接到它的客户端(两者都相同并接收数据作为输入)。我希望他们像聊天应用程序一样进行通信。
这是多线程类:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
/** * @author Fer */
public class ServidorMultithread {
public static void main(String[] args) {
new ServidorMultithread();
}
public ServidorMultithread() {
try {
ServerSocket serverSocket = new ServerSocket(8000);
InetAddress inetAdd = serverSocket.getInetAddress();
int clientNo = 1;
while (true) {
Socket s = serverSocket.accept();
InetAddress inetAddress = s.getInetAddress();
//System.out.println("InetAddres: "+ inetAddress);
HandleAClient task = new HandleAClient(s);
new Thread(task).start();
clientNo++;
//System.out.println("Client: "+ clientNo);
}
}
catch(IOException ex) {
System.err.println(ex);
}
}
class HandleAClient implements Runnable {
private Socket socket; // A connected socket
public HandleAClient(Socket socket) {
this.socket = socket;
}
public void run() {
try {
DataInputStream inputFromClient = new DataInputStream(
socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(
socket.getOutputStream());
while (true) {
//double number = inputFromClient.readDouble();
String texto = inputFromClient.toString();
outputToClient.writeChars(texto.toString());
//System.out.println("Me: " + textos'\n');
System.out.println("Texto: " + texto.toString() + '\n');
}
}
catch(IOException e) {
System.err.println(e);
}
}
}
}
这是客户端类(两个客户端都相同):
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.awt.event.*;
import java.io.IOException;
import java.net.Socket;
public class MyCliente extends javax.swing.JFrame {
/**
* Creates new form MyCliente
*/
public MyCliente() {
initComponents();
sendButton.addActionListener(new ButtonListener());
jTextField1.addActionListener(new ButtonListener());
try{
Socket s = new Socket("localhost", 8000);
fromServer = new DataInputStream(s.getInputStream());
toServer = new DataOutputStream(s.getOutputStream());
}
catch(Exception ex){
System.out.println("There was something wrong with creating a socket");
}
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
sendButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.GridLayout(1, 0));
jLabel1.setText("Message:");
jTextField1.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
sendButton.setText("Send");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 406, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sendButton)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(sendButton))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
getContentPane().add(jPanel1);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
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 ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MyCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MyCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MyCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MyCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyCliente().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JButton sendButton;
// End of variables declaration
private DataOutputStream toServer;
private DataInputStream fromServer;
private class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
//double number = Double.parseDouble(jTextField1.getText().trim());
String texto = jTextField1.getText();
jTextField1.setText("");
try {
toServer.writeChars(texto);
toServer.flush();
String result = fromServer.toString();
jTextArea1.append("ME: "+ texto+"\n");
//jTextArea1.append("Other: "+fromServer.toString()+"\n");
} catch (IOException ex) {
System.out.println("There was something wrong with creating a socket");
}
}
}
}
我无法找到在这个多线程中建立这两个客户端之间连接的方法。
我该怎么做?