【发布时间】:2024-04-25 01:40:02
【问题描述】:
我一直在尝试从一个简单的客户端向一个简单的服务器发送一个 tcp/ip 数据包...
当我在 netbeans 中运行它们时,我得到了服务器的响应,但我在 wireshark 中找不到数据包,如果我在 cmd 中使用 netstat 命令,数据包似乎也不存在...... 我尝试了几个不同的端口(8080,80,5000,...),并且作为 ip 地址,我使用的是 localhost。
netbeans 或 wireshark 中是否有一些我错过的设置,我仍然需要配置?
客户:
public class TCPClient {
private static InetAddress host;
private static final int PORT=1235;
public static void main(String[] args)
{
try
{
host=InetAddress.getByName("localhost");
}
catch(UnknownHostException e)
{
System.out.println("Host id not found");
System.exit(1);
}
run();
}
private static void run()
{
Socket link=null;
try
{
link = new Socket(host,PORT);
BufferedReader in = new BufferedReader
(new InputStreamReader(link.getInputStream()));
PrintWriter out = new PrintWriter(link.getOutputStream(),true);
BufferedReader userEntry = new BufferedReader
(new InputStreamReader(System.in));
String message,response;
do
{
System.out.println("Enter message: ");
message=userEntry.readLine();
out.println(message);
response=in.readLine();
System.out.println("\nSERVER> " + response);
}
while(!message.equals("***CLOSE***"));
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
System.out.println("\n* Closing connection... *");
link.close();
}
catch(IOException e)
{
System.out.println("unable to disconnect!");
System.exit(1);
}
}
}
服务器:
public class TCPServer {
private static ServerSocket serverSock;
private static final int PORT = 1235;
public static void main(String[] args)
{
System.out.println("opening port...\n");
try
{
serverSock=new ServerSocket(PORT);
}
catch(IOException e)
{
System.out.println("unable to attach port");
System.exit(1);
}
do
{
run();
}
while(true);
}
private static void run()
{
Socket link=null;
try
{
link = serverSock.accept();
BufferedReader in = new BufferedReader
(new InputStreamReader(link.getInputStream()));
PrintWriter out = new PrintWriter(link.getOutputStream(),true);
int numMessages=0;
String message = in.readLine();
while(!message.equals("***CLOSE***"))
{
System.out.println("Message received.");
numMessages++;
out.println("Message " + numMessages + ": " + message);
message=in.readLine();
}
out.println(numMessages + " messages received");
}
catch(IOException e)
{
System.out.println("unable to disconnect!");
System.exit(1);
}
}
}
【问题讨论】:
-
嗯,你需要监听环回接口,而不是你在wireshark中的实际网络接口。
-
有没有简单的方法在 Windows 上做到这一点? lo 没有出现在我的接口列表之间