我正在尝试构建一个允许远程PC控制的软件。当客户端和服务器都在同一台PC上时,我的代码到目前为止能够共享服务器屏幕,但它显示“连接被拒绝”错误当我尝试将客户端和服务器保存在不同的笔记本电脑中时。
public static void main(String args[]) throws IOException,
ClassNotFoundException {
DrawGui();
ServerSocket ss = new ServerSocket(3389);
//Socket server = ss.accept();
while(true)
{
Socket server = ss.accept();
new ReceiveScreenshots(server,frame,desktop,inter,panel,label);
}
}
我被建议将ss.accept()保留在while循环之外。但是,如果我将代码更改为以下内容并将ss.accept()保留在while循环之外,则我的代码会显示许多错误。
public static void main(String args[]) throws IOException, ClassNotFoundException {
DrawGui();
ServerSocket ss = new ServerSocket(3389);
Socket server = ss.accept();
while(true)
{
//Socket server = ss.accept();
new ReceiveScreenshots(server,frame,desktop,inter,panel,label);
}
}
有人可以帮我吗?以下是客户端的代码
public class Test {
public static void main(String args[]) throws AWTException, IOException
{
Socket s = new Socket("localhost",3389);
Robot robot = null;
GraphicsEnvironment gen = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gdev = gen.getDefaultScreenDevice();
robot = new Robot(gdev);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rectangle = new Rectangle(dim);
new Client(s,robot,rectangle);
}
}
public class Client extends Thread {
Socket s;
Rectangle rectangle = null;
Robot robot = null;
ImageIcon previous = new ImageIcon();
public Client(Socket s, Robot robot, Rectangle rectangle) {
this.s = s;
this.rectangle = rectangle;
this.robot = robot;
start();
}
public void run() {
ObjectOutputStream ous = null;
try {
ous = new ObjectOutputStream(s.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
while (true) {
BufferedImage bImage = robot.createScreenCapture(rectangle);
ImageIcon image = new ImageIcon(bImage);
if(previous.equals(image))
continue;
else
{
try {
System.out.println("before sending image");
ous.writeObject(image);
System.out.println(" image sent");
ous.reset();
System.out.println(" stream reset");
previous = image;
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}}
}
这里没有可以抛出ConnectException: connection refused
的代码,但这意味着没有任何东西正在侦听目标IP:端口。
你被'建议保持ss.accept()
不受while
循环'的影响?基于什么理由?
Socket s = new Socket("localhost",3389);
此代码仅在服务器位于本地主机中时才有效。如果不是,则必须提供IP地址或主机名,而不是"localhost"
。当然这很明显?