本toy程序使用socket,后续键入多线程,仅为讲解其原理:
ChatClient.java[java]
package chat;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author gavin
*/
public class ChatClient extends Frame {
Socket s = null;
TextField tf = new TextField();
TextArea ta = new TextArea();
DataOutputStream dOut = null;
public static void main(String[] args) {
ChatClient clt = new ChatClient();
clt.lanuchFrame();
}
public void lanuchFrame() {
connectServer();
this.setLocation(400, 300);
this.setSize(300, 300);
add(this.tf, BorderLayout.SOUTH);
add(ta, BorderLayout.NORTH);
pack();
this.setVisible(true);
TextFieldListener tl = new TextFieldListener();
tf.addActionListener(tl);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
connectClose();
System.exit(0);
}
});
}
public void connectServer() {
try {
s = new Socket("localhost", 8080);
System.out.println("success connected");
} catch (UnknownHostException ex) {
System.out.println("host error");
} catch (IOException ex) {
System.out.println("IO error");
}
}
public void connectClose() {
try {
dOut.close();
s.close();
} catch (IOException ex) {
Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
private class TextFieldListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
String message = tf.getText().trim();
ta.setText(message);
tf.setText("");
try {
dOut = new DataOutputStream(s.getOutputStream());
dOut.writeUTF(message);
} catch (IOException ex) {
Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}[/java]
ChatServer.java[java]
package chat;
import java.io.IOException;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author gavin
*/
public class ChatServer {
static ServerSocket ss = null;
static Socket s = null;
static DataInputStream dataIn = null;
public static void main(String[] args) {
try {
ss = new ServerSocket(8080);
s = ss.accept();
System.out.println("a client had connected!");
} catch (IOException ex) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
try {
while (true) {
dataIn = new DataInputStream(s.getInputStream());
String message = dataIn.readUTF();
System.out.println(message);
}
} catch (IOException ex) {
System.out.println("Client Closed");
} finally {
try {
if (dataIn != null) {
dataIn.close();
}
if (s != null) {
s.close();
}
} catch (IOException ex1) {
Logger.getLogger(ChatServer.class.getName()).log(Level.SEVERE, null, ex1);
}
}
}
}[/java]