Server端:
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class TalkServer
{
public static void main(String[] args)
{
new MyFrame("Server Talking:");
}
}
class MyFrame extends Frame
{
TextField content,sendText;
Button send;
Panel p;
ServerSocket server=new ServerSocket(8887);
Socket s=server.accept();
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
DataInputStream dis=new DataInputStream(s.getInputStream());
MyFrame(String title)
{
super(title);
content=new TextField(" ");
sendText=new TextField(" ");
send=new Button("发送");
send.addActionListenner(new ActionMonitor());
p=new Panel(new GridLayout(1,2));
add(content,"North");
p.add(sendText);
p.add(send);
add(p,"South");
pack();
addActionListener(new FActionMonitor());
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setVisible(true);
}
class FActionMonitor implements ActionListener
{
content.setText(content.getText+dis.readUTF());
}
class ActionMonitor implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
dos.writeUTF(sendText.getText());
content.setText(content.getText()+sendText.getText());
}
}
}
客户端:
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class TalkCleint
{
public static void main(String[] args)
{
new MyFrame1("Client Talking...");
}
}
class MyFrame1 extends Frame
{
TextField content,sendText;
Button send;
Panel p;
Socket server=new ServerSocket("127.0.0.1",8887);
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
DataInputStream dis=new DataInputStream(s.getInputStream());
MyFrame1(String title)
{
super(title);
content=new TextField();
sendText=new TextField();
send=new Button("发送");
send.addActionListener(new ActionMonitor());
p=new Panel(new GridLayout(1,2));
add(content,"North");
p.add(sendText);
p.add(send);
add(p,"South");
pack();
addActionListener(new FActionMonitor());
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setVisible(true);
}
class FActionMonitor implements ActionListener
{
String s=content.getText();
content.setText(s+dis.readUTF());
}
class ActionMonitor implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
dos.writeUTF(sendText.getText());
String s=content.getText();
content.setText(s+(sendText.getText()));
}
}
}