String ip = "127.0.0.1"
int port = 1234
try {
Socket socket = new Socket(ip, port)
socket.setSoTimeout(5539900)
java.io.OutputStream out = socket.getOutputStream()
byte[] date = "hello world".getBytes()
out.write(data)
out.flush()
byte[] buffer = new byte[1024]
int len = -1
java.io.FileOutputStream fout = new java.io.FileOutputStream(
"d:/response.txt")
java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream()
java.io.InputStream in = socket.getInputStream()
while ((len = in.read(buffer, 0, buffer.length)) >0) {
bout.write(buffer, 0, len)
}
in.close()
bout.flush()
bout.close()
byte[] rdata = bout.toByteArray()
System.out.println(new String(rdata))
fout.write(rdata)
fout.flush()
fout.close()
socket.close()
} catch (UnknownHostException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
}
}
服务器端的
ServerSocket ss = new ServerSocket(1234)
Socket socket=null
BufferedReader in
PrintWriter out
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()
}
1.调用系统命令, netstat -ano| grep <端口号>(linux)如果有记录则说明该端口被占用。2.试图建立该端口号的socket链接。如果返回端口已绑定的错误,就说明被占了。
用 cmdexe 程序来输入命令: netstat -ano | find ":你的端口号"找到了的话: taskkill /f /pid:你的进程PID(在上一条命令行中会列出进程PID) 正常的情况下,如果你的程序真的已经退出了,那个端口就会自动被 *** 作系统释放的,很可能你的程序还java 用ServerSocket监听了一个端口,在程序结束的欢迎分享,转载请注明来源:内存溢出
评论列表(0条)