gpt4 book ai didi

java - UDP聊天问题

转载 作者:行者123 更新时间:2023-12-02 08:34:30 27 4
gpt4 key购买 nike

friend 们大家好,我创建了一个 UDP 聊天程序,客户端可以通过该程序通过 LAN 进行通信。

我创建了一个通用程序,即我使用不同的端口号运行相同的代码。和 LAN 上的 IP 地址

我的问题是,下面的代码在本地主机上运行良好,但是当我尝试连接两台机器时,该代码不起作用..没有错误,但两个客户端仍然无法通信

我也关闭了防火墙。但我无法找出为什么我无法在两台机器之间通信

代码如下::

    import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;

class ChatApplDG extends Frame implements ActionListener
{

TextField tf = new TextField(50);
Button btn = new Button("Send");
Button exit = new Button("Exit");
TextArea ta = new TextArea(50,10);
int fromPort, toPort;
String hostName;

DatagramSocket dgSock;

public static void main(String args[]) throws Exception
{
ChatApplDG ca = new ChatApplDG();
ca.startClient(args[0],Integer.parseInt(args[1]),Integer.parseInt(args[2]));
}

ChatApplDG()
{
Panel p = new Panel();
add(p,BorderLayout.NORTH);
p.add(tf);
p.add(btn);
p.add(exit);
add(ta,BorderLayout.CENTER);
btn.addActionListener(this);
exit.addActionListener(this);
setSize(500,300);
show();
ta.setEditable(false);
}

void startClient(String hName,int fPort,int tPort)
{
try
{
hostName = hName;
fromPort=fPort;
toPort=tPort;
dgSock = new DatagramSocket(fromPort);
ta.append("Ready To Send ...\n");
RunningThreadDG rt = new RunningThreadDG(dgSock,ta);
Thread thread = new Thread(rt);
thread.start();
}
catch(Exception e)
{
}
}


public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==btn)
{
try
{
byte buff[] = new byte[500];
InetAddress remoteHost = InetAddress.getByName(hostName);
buff=tf.getText().getBytes();
dgSock.send(new DatagramPacket(buff,buff.length,remoteHost.getLocalHost(),toPort));
ta.append("Send : " + tf.getText() + "\n");
tf.setText("");
}
catch(Exception e)
{
}
}
else
{
System.exit(0);
}
}
}


class RunningThreadDG extends Frame implements Runnable
{
DatagramSocket dgSock;
TextArea ta;
String str;

RunningThreadDG(DatagramSocket dgs,TextArea t)
{
dgSock=dgs;
ta=t;
}

public void run()
{
byte[] buff = new byte[500];
while(true)
{
try
{
DatagramPacket dgPack = new DatagramPacket(buff,buff.length);
dgSock.receive(dgPack);
ta.append("Received : " + new String(dgPack.getData(),0,dgPack.getLength()) + "\n");
}
catch(Exception e)
{
}
}
}
}

最佳答案

这里有一个问题:

dgSock.send(new DatagramPacket(buff,buff.length,remoteHost.getLocalHost(),toPort));

remoteHost.getLocalHost() 返回本地主机的 InetAddress。尝试仅传递 remoteHost 而不是 remoteHost.getLocalHost():

dgSock.send(new DatagramPacket(buff,buff.length,remoteHost,toPort));

关于java - UDP聊天问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2324624/

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