求救!小弟写了一个java的服务端部分,但是无法正常关闭。

来源:互联网 发布:无线路由访客网络 编辑:程序博客网 时间:2024/05/16 10:32
写了一个socket服务端程序,但是加入界面之后,程序关闭之后端口一直无法关闭。好像是socket端口关闭有问题,求修正方法源程序如下code=Java]import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;

import javax.swing.JOptionPane;

public class Se1 extends WindowAdapter implements ActionListener {
private ServerSocket server;

private Socket socket;

private BufferedReader in;

private PrintWriter out;

JFrame f;

JPanel p;

JButton b1, b2, b3;

JTextField tf;

public Se1() {
f = new JFrame("Socked Server");
b1 = new JButton("Agree!");
b1.setActionCommand("agree");
b1.addActionListener(this);
b2 = new JButton("Disagree!");
b2.setActionCommand("disagree");
b2.addActionListener(this);
b3 = new JButton("Connect!");
b3.setActionCommand("connect");
b3.addActionListener(this);
p = new JPanel();
p.add(b1);
p.add(b2);
p.add(b3);
f.getContentPane().add(p, "North");
tf = new JTextField();
f.getContentPane().add(tf, "Center");
f.setSize(400, 150);
f.setVisible(true);
try {
server = new ServerSocket(10000);
while (true) {
socket = server.accept();
String RemoteIp = socket.getInetAddress().getHostAddress();
String RemotePort = " : " + socket.getLocalPort();
tf.setText("有学生想申请使用投影仪!  IP: " + RemoteIp + " Port"
+ RemotePort);
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
String line = in.readLine();
String[] student = line.split(",");
tf.setText("该学生名字: " + student[0] + "   座位号: " + student[1]
+ "\n" + " 是否允许该学生使用投影仪?");

// System.out.println("该学生名字 : " + line);
// out.println("your message received " );
// String st = JOptionPane.showInputDialog("permit or not ?");
// System.out.println("是否允许该学生使用投影仪?");
// BufferedReader st = new BufferedReader(new
// InputStreamReader(System.in));
//
// out.println(st.readLine());
//
// out.close();
// in.close();
// socket.close();
}
} catch (IOException ex) {
out.println("出错");
}

}

public static void main(String[] args) {
Server be = new Server();
// be.Server();
}

public void actionPerformed(ActionEvent e) {
String s1 = "同意请求!", s5 = "本机连接";
String s2 = "拒绝请求!";
String s3 = "yes", s4 = "no";
if (e.getActionCommand() == "agree") {
tf.setText(s1);
out.println(s3);
// out.close();
} else if (e.getActionCommand() == "disagree") {
tf.setText(s2);
out.println(s4);
// out.close();
} else if (e.getActionCommand() == "connect") {
java.lang.Process pro = null;
Runtime rt = Runtime.getRuntime();
tf.setText("本机打开投影仪");
String s = "\"C:\\NSC.exe\"";
try {
pro = rt.exec(s);
} catch (IOException ex) {
ex.printStackTrace();

}
}
}

/*public void windowClosed(WindowEvent e) {
try {
in.close();
out.close();
socket.close();
} catch (IOException ex) {
out.println("出错");
}
System.exit(0);
}*/
}
[/code]
0 0