希望只在服务端改动,相关代码如下:
服务端:
package cheat;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.Button;
import java.awt.event.*;
public class CheatServer {
public static void main(String[] args) {
new MyFrame("服务端");
}
}
class MyFrame extends Frame{
static boolean judge=true;
DataInputStream dis=null;
MyFrame(String s){
super(s);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
try {
dis.close();
} catch (IOException err) {
err.printStackTrace();
}
setVisible(false);
System.exit(0);
}
});
setLayout(new BorderLayout());
setBounds(200,200,250,300);
TextArea tr=new TextArea();
tr.setEditable(false);
Button b=new Button("终止");
Panel p=new Panel();
p.setLayout(new FlowLayout(FlowLayout.CENTER));
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ee){
judge=false;
tr.setText("服务终止\n");
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
p.add(b);
add("North",tr);
add("South",p);
setVisible(true);
try {
ServerSocket ss=new ServerSocket(6666);
while(judge){
Socket s1=ss.accept();
tr.append("用户接入成功!\n");
dis=new DataInputStream(s1.getInputStream());
while(judge){
String str=dis.readUTF();
System.out.println(str);
}
}
} catch (IOException er) {
tr.setText("服务出错!"+" ");
System.out.println(er.getMessage());
}
}
}
客户端(测试参考,不希望改动):
package cheat;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Button;
public class CheatClent{
public static void main(String[] args){
new MyFreame("客户端");
}
}
class MyFreame extends Frame{
Socket client=null;
DataOutputStream dos=null;
MyFreame(String s){
super(s);
setBounds(200,200,400,500);
setLayout(new BorderLayout());
TextArea tr=new TextArea();
tr.setEditable(false);
TextField tf=new TextField();
tf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
String str=tf.getText().trim();
tr.append(str+"\n");
tf.setText("");
try {
dos=new DataOutputStream(client.getOutputStream());
dos.writeUTF(str);
dos.flush();
} catch (IOException e) {
tr.setText("输出异常!\n");
}
}
});
add("North",tr);
add("South",tf);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
try {
dos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
setVisible(false);
System.exit(0);
}
});
setVisible(true);
try {
client=new Socket("127.0.0.1",6666);
tr.setText("连接成功!\n");
} catch (IOException er) {
tr.setText("连接出错!\n");
}
}
}