如题所述
用socket 去连这个端口,如果能连上,则表示端口被占用追问
Socket socket = new Socket("127.0.0.1",8080);
System.out.println("占用了");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (java.net.ConnectException e) {
e.printStackTrace();
System.out.println("没有占用");
} catch (IOException e) {
e.printStackTrace();
}追问
ServerSocket server = new ServerSocket(8080);
System.out.println("没有占");
} catch (IOException e) {
e.printStackTrace();
System.out.println("占着呢");
}
能否给段代码参考下?
追答try {Socket socket = new Socket("127.0.0.1",8080);
System.out.println("占用了");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (java.net.ConnectException e) {
e.printStackTrace();
System.out.println("没有占用");
} catch (IOException e) {
e.printStackTrace();
}追问
好的 我试试 谢谢
追答客气了,或是用 serverSocket
try {
ServerSocket server = new ServerSocket(8080);
System.out.println("没有占");
} catch (IOException e) {
e.printStackTrace();
System.out.println("占着呢");
}
温馨提示:答案为网友推荐,仅供参考
第1个回答 2013-04-12
建立一个服务监听socket
import java.net.*;import java.io.*;
public class Server
{
private ServerSocket ss;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public Server()
{
try
{
ss = new ServerSocket(10000);
while (true)
{
socket = ss.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);
String line = in.readLine();
out.println("you input is :" + line);
out.close();
in.close();
socket.close();
}
ss.close();
}
catch (IOException e)
{}
}
public static void main(String[] args)
{
new Server();
}
}
以上是一个示例。其中new ServerSocket(10000)中的10000就是指的端口,
如果该端口被占用的话,就会报异常。然后你就知道端口被占用了。
第2个回答 2013-04-12
我怎么知道、