服務端:
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;
MyFrame(String s){
super(s);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
setVisible(false);
System.exit(0);
}
});
setLayout(new BorderLayout());
setBounds(200,200,250,300);
TextArea tr=new TextArea();
tr.setEditable(true);
Button b=new Button("終止");
Panel p=new Panel();
p.setLayout(new FlowLayout(FlowLayout.CENTER));
try {
ServerSocket ss=new ServerSocket(8888);
while(judge){
Socket s1=ss.accept();
tr.append("用戶接入成功!"+" ");
}
} catch (IOException er) {
tr.setText("服務出錯!"+" ");// 為何跑出?
}
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ee){
judge=false;
tr.setText("服務終止");
}
});
p.add(b);
add("North",tr);
add("South",p);
setVisible(true);
}
}
客戶端:
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{
MyFreame(String s){
super(s);
setBounds(200,200,400,500);
setLayout(new BorderLayout());
TextArea tr=new TextArea();
tr.setEditable(false);
TextField tf=new TextField();
add("North",tr);
add("South",tf);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
setVisible(false);
System.exit(0);
}
});
setVisible(true);
try {
Socket client=new Socket("127.0.0.1",8888);
} catch (IOException er) {
tr.setText("連接出錯!");// 為何跑出?
}
}
}
程序功能確實不全,出現連接錯誤主要是因為你的運行步驟出錯了,應該先運行服務器端,創建了8888端口的serversocket,再運行客戶端,
才能連接上8888端口,這樣就不會出錯了。