DatagramSocket socket = new DatagramSocket(); int hostPort =socket.getLocalPort();//获取当前收发地址的端口 String hostIP = InetAddress.getLocalHost().getHostAddress();
时间: 2023-12-06 13:43:09 浏览: 98
这段代码创建了一个 DatagramSocket 对象,并通过该对象获取了当前收发地址的端口号和本机的 IP 地址。
具体来说,第一行代码创建了一个 DatagramSocket 对象,该对象可以用于发送和接收 UDP 数据报。在创建 DatagramSocket 对象时,如果不指定端口号和 IP 地址,系统会自动分配一个空闲的端口号和本机的 IP 地址。
第二行代码调用 `getLocalPort()` 方法获取当前 DatagramSocket 对象绑定的端口号。
第三行代码使用 `InetAddress.getLocalHost().getHostAddress()` 方法获取本机的 IP 地址。`InetAddress.getLocalHost()` 方法返回一个表示本机的 InetAddress 对象,`getHostAddress()` 方法返回该 InetAddress 对象对应的 IP 地址。
相关问题
优化下面代码package Zzz; import java.awt.TexturePaint; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.text.BreakIterator; import java.util.Scanner; import javax.imageio.metadata.IIOInvalidTreeException; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.sound.sampled.Port; import org.omg.CORBA.INTERNAL; public class Test3{ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Scanner scanner=new Scanner(System.in); System.out.print("请输入对方的IP地址"); String ipAddress=scanner.nextLine(); InetAddress ip=InetAddress.getByName(ipAddress); System.out.print("请输入对方的端口号"); int toPort=scanner.nextInt(); System.out.print("请输入本地接受的端口号:"); int listenPort=scanner.nextInt(); new Thread(); new Thread(); } } class SendThread implements Runnable{ private int Port; private InetAddress ip; public SendThread(int Port,InetAddress ip) { this.ip=ip; this.Port=Port; // TODO Auto-generated constructor stub } @Override public void run() { // TODO Auto-generated method stub try { Scanner scanner=new Scanner(System.in); DatagramSocket socket=new DatagramSocket(); System.out.println("开始聊天"); DatagramPacket packet=new DatagramPacket(new byte[1024], 1024, ip, Port); while(true){ String zyk=scanner.nextLine(); packet.setData(zyk.getBytes()); socket.send(packet); if (zyk.equals("bye")) { break; } } System.out.println("退出聊天"); socket.close(); } catch (Exception e) { // TODO: handle exception } } } class RecieveThread implements Runnable{ private int Port; public RecieveThread(int Port){ this.Port=Port; } @Override public void run() { while(true){ try { DatagramSocket socket=n
首先,你的代码存在一些问题,例如创建线程时没有指定线程任务,变量名不规范等等。以下是我对你的代码进行的优化:
1. 对变量名进行规范化,使其更易读懂。
2. 需要创建两个线程,一个用于发送消息,一个用于接收消息。因此我们需要在主线程中创建这两个线程,并且需要为它们指定任务。
3. 在发送消息的线程中,我们需要不断地从控制台读取用户输入,然后将其发送出去。需要注意的是,我们需要在循环中不断更新 DatagramPacket 对象中的数据部分。
4. 在接收消息的线程中,我们需要不断地接收来自对方的消息,并在控制台上输出。同样需要注意的是,在循环中需要不断更新 DatagramPacket 对象中的数据部分。
下面是优化后的代码:
```
package Zzz;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入对方的IP地址:");
String ipAddress = scanner.nextLine();
InetAddress ip = InetAddress.getByName(ipAddress);
System.out.print("请输入对方的端口号:");
int toPort = scanner.nextInt();
System.out.print("请输入本地接受的端口号:");
int listenPort = scanner.nextInt();
DatagramSocket socket = new DatagramSocket(listenPort);
Thread sendThread = new Thread(new SendTask(socket, ip, toPort));
Thread receiveThread = new Thread(new ReceiveTask(socket));
sendThread.start();
receiveThread.start();
}
}
class SendTask implements Runnable {
private final DatagramSocket socket;
private final InetAddress ip;
private final int toPort;
public SendTask(DatagramSocket socket, InetAddress ip, int toPort) {
this.socket = socket;
this.ip = ip;
this.toPort = toPort;
}
@Override
public void run() {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("开始聊天");
while (true) {
String message = scanner.nextLine();
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, ip, toPort);
socket.send(packet);
if (message.equals("bye")) {
break;
}
}
System.out.println("退出聊天");
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
}
class ReceiveTask implements Runnable {
private final DatagramSocket socket;
public ReceiveTask(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("对方说: " + message);
if (message.equals("bye")) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
}
```
希望这些改进能帮助你更好地理解和使用该代码!
import java.io. *; import java.net.*; import java.util. *; public class EchoServer{ public static void main(String[] args) throws IOException {new EchoServerThread().start();}} class EchoServerThread extends Thread{ protected DatagramSocket socket = null; protected BufferedReader in = null; protected boolean hasMoreWork = true; protected int number = 0;//访问计数变量 public EchoServerThread() throws IOException{ this("EchoServerThread"); } public EchoServerThread(String name) throws IOException{ super(name); socket = new DatagramSocket(4248); public void run(){ while (hasMoreWork) { try{ byte[] buf = new byte[256];//接收应答 DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); //创建应答 String dString = null; number++; dString ="Hi!你是第"+ number + "个访问者!"; buf = dString.getBytes();//将应答发送给端口和地址为"address""port"的客户 InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); }catch (IOException e){ e.printStackTrace(); hasMoreWork = false; } } socket.close();} } }哪里出错了
代码中有几个语法错误:
1. 在 EchoServerThread 构造函数中没有关闭构造函数的大括号。
2. run() 函数中没有关闭while循环的大括号。
3. 在 run() 函数中,未在 EchoServerThread 类之前添加 public 关键字。
下面是修改后的代码:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
new EchoServerThread().start();
}
}
class EchoServerThread extends Thread {
protected DatagramSocket socket = null;
protected BufferedReader in = null;
protected boolean hasMoreWork = true;
protected int number = 0; // 访问计数变量
public EchoServerThread() throws IOException {
this("EchoServerThread");
}
public EchoServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4248);
}
public void run() {
while (hasMoreWork) {
try {
byte[] buf = new byte[256]; // 接收应答
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet); // 创建应答
String dString = null;
number++;
dString = "Hi!你是第" + number + "个访问者!";
buf = dString.getBytes(); // 将应答发送给端口和地址为"address" "port"的客户
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
hasMoreWork = false;
}
}
socket.close();
}
}
```
阅读全文