日期:2014-05-20 浏览次数:20849 次
import java.net.*;
import java.io.*;
public class ChatServer {
/**
* @param args
*/
public static void main(String[] args) {
try{
ServerSocket ss = new ServerSocket(8888);
while(true){
Socket s = ss.accept();
System.out.println("Server has connected!");
System.out.println(s);
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis);
System.out.println("ddddddddd");
String str = dis.readUTF();
System.out.println(str);
dis.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket s = null;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
this.setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent arg0){
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
}
public void connect(){
try{
s = new Socket("127.0.0.1", 8888);
System.out.println(s);
System.out.println("Client has connected!");
}
catch(UnknownHostException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
private class TFListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
taContent.setText(str);
tfTxt.setText("");
try{
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
System.out.println(str);
System.out.println(dos);
dos.flush();
dos.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
}