工作三年,我一直想用java写一个聊天室,最近不忙,终于忍不住开始动手写了:具体思路:1:服务器用java.net.ServerSocket监听特定端口,客户端连接服务器,我用的工具是:netbean6.0+jdk1.6,下面是三个类,说明一下,服务器也是界面,所以必须写一个线程类单独启动一个线程进行端口的监听。我写的不好的地方希望高手给予指点,现在只实现服务器接收信息,我会努力完成全部功能。(注意一下:必须在jdk1.6下面才可以运行,有几个类是jdk1.5里面没有的。)
第一个:ServerWindow.java服务器界面:
package ftpupload;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.Thread;
import java.net.ServerSocket;
/*
* ServerWindow.java
*
* Created on 2008年5月7日, 上午10:00
*/
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author DELL
*/
public class ServerWindow extends javax.swing.JFrame {
/** Creates new form ServerWindow */
public ServerWindow() {
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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
messageDisplay = new javax.swing.JTextArea();
jPanel1 = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
sendMessage = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
jTree1 = new javax.swing.JTree();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("服务器");
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
messageDisplay.setColumns(20);
messageDisplay.setRows(5);
messageDisplay.setName("messageDisplay"); // NOI18N
jScrollPane1.setViewportView(messageDisplay);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel1.setPreferredSize(new java.awt.Dimension(100, 50));
jButton2.setText("清空");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
sendMessage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendMessageActionPerformed(evt);
}
});
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()
.addComponent(sendMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 548, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(sendMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jButton1.getAccessibleContext().setAccessibleName("send");
getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
jScrollPane2.setViewportView(jTree1);
getContentPane().add(jScrollPane2, java.awt.BorderLayout.LINE_END);
pack();
}// </editor-fold>
private void formComponentShown(java.awt.event.ComponentEvent evt) {
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void sendMessageActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
ServerWindow serverWindow = new ServerWindow();
serverWindow.setVisible(true);
}
});
}
public javax.swing.JTextArea getMessageDisplay(){
return this.messageDisplay;
}
public void setMessageDisplay(javax.swing.JTextArea messageDisplay){
this.messageDisplay=messageDisplay;
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTree jTree1;
private javax.swing.JTextArea messageDisplay;
private javax.swing.JTextField sendMessage;
// End of variables declaration
}
第二个:ServerThread.java 服务器监听线程:
package ftpupload;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerThread extends Thread{
private ServerSocket serverSocket;
private Socket socket;
private int port=12345;
public void run(){
ServerWindow serverWindow=new ServerWindow();
serverWindow.setVisible(true);
initServer(serverWindow);
}
void initServer(ServerWindow serverWindow){
try {
serverSocket = new ServerSocket(port);
while(true){
socket=serverSocket.accept();
if(socket.isConnected()){
BufferedReader breader = new BufferedReader(new java.io.InputStreamReader(socket.getInputStream()));
serverWindow.getMessageDisplay().append(breader.readLine());
}
}
} catch (IOException ex) {
Logger.getLogger(ServerWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]){
new ServerThread().run();
}
}
第三个:ClientWindow.java 客户端线程:
/*
* ClientWindow.java
*
* Created on 2008年5月7日, 上午10:19
*/
package ftpupload;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author DELL
*/
public class ClientWindow extends javax.swing.JFrame {
/** Creates new form ClientWindow */
private int port = 12345;
private String ip = "localhost";
private Socket socket ;
public ClientWindow() {
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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jPanel1 = new javax.swing.JPanel();
sendMessage = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTree1 = new javax.swing.JTree();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("客户端");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel1.setPreferredSize(new java.awt.Dimension(100, 50));
sendMessage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendMessageActionPerformed(evt);
}
});
jButton1.setText("发送");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("清空");
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()
.addComponent(sendMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(11, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(sendMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);
jScrollPane2.setViewportView(jTree1);
getContentPane().add(jScrollPane2, java.awt.BorderLayout.LINE_END);
pack();
}// </editor-fold>
private void sendMessageActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
sendMessage(sendMessage.getText());
}
public void sendMessage(String text){
try {
socket = new Socket(ip, port);
System.out.println("连接状态"+socket.isConnected());
if (socket.isConnected()) {
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println(text);
}
} catch (UnknownHostException ex) {
Logger.getLogger(ClientWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ClientWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClientWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTree jTree1;
private javax.swing.JTextField sendMessage;
// End of variables declaration
}