gpt4 book ai didi

Java Web 客户端远程连接

转载 作者:行者123 更新时间:2023-12-01 17:48:59 26 4
gpt4 key购买 nike

我正在编写一个网络服务器/客户端。通过本地主机进行通信时,一切都很好。但是当使用我的公共(public)IP地址进行通信时,会抛出异常。这是一个最小的工作示例:

import java.io.*; 
import java.text.*;
import java.util.*;
import java.net.*;

public class Server
{
public static void main(String[] args) throws IOException
{
int port = 80;

// server is listening on port
ServerSocket ss = new ServerSocket(port);

// running infinite loop for getting
// client request
while (true)
{
Socket s = null;

try
{
// socket object to receive incoming client requests
s = ss.accept();

System.out.println("A new client is connected : " + s);

// obtaining input and out streams
ObjectOutputStream odos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream odis = new ObjectInputStream(s.getInputStream());

Info info = new Info();
info.color = 1;
odos.writeObject(info);

while(true){
info = (Info)odis.readObject();
if(info.exit){
break;
}
}

// closing resources
odis.close();
odos.close();


}
catch (Exception e){
s.close();
e.printStackTrace();
}
}
}
}

客户:

import java.util.*; 
import java.net.*;
import java.io.*;
import java.net.InetAddress;
public class Client
{
public static void main(String[] args) {
if(args.length>0){
ip_name = args[0];
}
if(args.length>1){
port = Integer.parseInt(args[1]);
}
network();
}

private static String ip_name = "localhost";
private static int port = 80;

private static void network(){

try
{
System.out.println("Connecting to network");

InetAddress ip = InetAddress.getByName(ip_name);

// establish the connection with server port
Socket s = new Socket(ip, port);
System.out.println("Connected");

// obtaining input and out streams
ObjectOutputStream odos = new ObjectOutputStream(s.getOutputStream());
InputStream i = s.getInputStream();

ObjectInputStream odis = new ObjectInputStream(i);

// get what color we are
int color = ((Info)odis.readObject()).color;
System.out.println(color);

//say we are done
Info info = new Info();
info.exit = true;
odos.writeObject(info);

System.out.println("Shutting down");


}catch(Exception e){
e.printStackTrace();
}
}
}

当使用本地主机时,客户端按预期打印出:

Connecting to network
Connected
1
Shutting down

但是当我用我的公共(public) IP 替换 localhost 时:

Connecting to network
Connected
java.io.StreamCorruptedException: invalid stream header: 48545450
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Client.network(Client.java:36)
at Client.main(Client.java:14)

48545450 是“HTTP”的十六进制,但除此之外我无法判断问题是什么。有什么想法吗?

最佳答案

当我尝试运行您的代码时,出现错误“信息不可序列化”。我已将您的 Info 类修改如下。

import java.io.Serializable;

public class Info implements Serializable {
public int color;
public boolean exit;
}

如果您要发送类数据,则需要实现Serializable。使用它,您可以通过网络保留对象信息。

关于Java Web 客户端远程连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60823118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com