📄 commandrunner.java
字号:
import java.net.*;
import java.io.*;
import java.util.*;
class CommandRunner implements Runnable
{
static String m_strFilter = "";
Socket m_sock;
final public void run()
{
try
{
// get the ip address of the client
String strClient = m_sock.getInetAddress().toString();
// exit the thread if client ip address does not have
// permission to access this server
// (you can add more complicated security here)
if(!m_strFilter.equals("")&&strClient.indexOf(m_strFilter)<0)
{
m_sock.close();
System.out.println("Connection closed: "+strClient);
return;
}
// open input and output streams to the client
BufferedInputStream inStream = new BufferedInputStream(m_sock.getInputStream());
BufferedOutputStream outStream = new BufferedOutputStream(m_sock.getOutputStream());
try
{
while(true)
{
// receive the command from the client
byte[] pCommand = SockData.Read(inStream);
// end the thread if no command is received
if(pCommand.length==0) return;
// receive the input to the command from the client
byte[] pInput = SockData.Read(inStream);
// print what has been received from the client
System.out.print("Client '"+strClient+"' executed command '"+new String(pCommand)+"' with input '"+new String(pInput)+"'\r\n");
// create a process for the command
Process proc = Runtime.getRuntime().exec(new String(pCommand),null);
// write the input to the created process
if(pInput.length>0)
{
BufferedOutputStream out = new BufferedOutputStream(proc.getOutputStream());
out.write(pInput);
out.write("\r\n".getBytes());
out.close();
}
// open output and error streams of the created process
BufferedInputStream in = new BufferedInputStream(proc.getInputStream());
BufferedInputStream err = new BufferedInputStream(proc.getErrorStream());
// send output and error from the created process to client
int nOut = 0;
int nErr = 0;
int nSize = 64*1024;
byte[] pBuffer = new byte[nSize];
while(nOut>=0||nErr>=0)
{
// read and send normal output
nOut = in.read(pBuffer,0,nSize);
while(nOut>0)
{
SockData.Write(outStream,pBuffer,nOut);
Thread.currentThread().sleep(100);
nOut = in.read(pBuffer,0,nSize);
}
// read and send error output
nErr = err.read(pBuffer,0,nSize);
while(nErr>0)
{
SockData.Write(outStream,pBuffer,nOut);
Thread.currentThread().sleep(100);
nErr = err.read(pBuffer,0,nSize);
}
// sleep a while to avoid burning too much CPU
Thread.currentThread().sleep(100);
}
// write end of output data
SockData.Write(outStream,null,0);
// clean up
in.close();
err.close();
proc.destroy();
}
}
catch(Exception e)
{
// send exception info to client
byte[] pError = (e.getMessage()+"\r\n").getBytes();
SockData.Write(outStream,pError,pError.length);
// write end of output data
SockData.Write(outStream,null,0);
}
// close connection to client
outStream.close();
inStream.close();
m_sock.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -