[英]Java Web Client Remote Connection
我正在編寫一個 Web 服務器/客戶端。 通過本地主機通信時,一切正常。 但是當使用我的公共 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();
}
}
}
使用 localhost 時,客戶端按預期打印:
Connecting to network
Connected
1
Shutting down
但是當我用我的公共 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
。 使用它,您可以通過網絡保留對象信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.