欢迎关注我的B站账号:卍卍子非鱼卍卍
文章目录
网络通信InetAddress实例客户端服务器端
网络通信
InetAddress
InetAddress.getLocalHost() 返回本地主机的InetAddress对象
host.getHostName() 获取主机名
host.getHostAddress() 获取主机ip地址
使用以上方法可能会抛出UnknownHostException异常,表示主机不存在
InetAddress host
;
try {
host
= InetAddress
.getLocalHost();
String hostname
= host
.getHostName();
String ip
= host
.getHostAddress();
} catch(UnknownHostException e
) {
e
.printStackTrace();
}
实例
下面的实例实现了客户端与服务器端的通信,客户端接收用户输入的字符串传递给服务器端,服务器端读取字符串,显示在终端上并返回给客户端,客户端接收到服务器端发来的字符串同样显示在终端上,双方接收到".QUIT"时结束通信
客户端
import java
.net
.*
;
import java
.io
.*
;
public class ClientTest {
public static void main(String
[] args
) {
try {
Socket client
= new Socket("127.0.0.1", 8001);
System
.out
.println("连接已建立");
DataInputStream in
= new DataInputStream(client
.getInputStream());
DataOutputStream out
= new DataOutputStream(client
.getOutputStream());
String line
= "";
while (!line
.equalsIgnoreCase(".QUIT")) {
System
.out
.println("输入消息:");
line
= readLine();
System
.out
.println("正在向服务器发送数据");
out
.writeUTF(line
);
System
.out
.println("正在等待服务器响应数据");
line
= in
.readUTF();
System
.out
.println("接收数据:" + line
);
}
in
.close();
out
.close();
client
.close();
} catch (Exception e
) {
System
.out
.println(e
.getMessage());
}
}
public static String
readLine() {
String str
= "";
BufferedReader in
= new BufferedReader(new InputStreamReader(System
.in
));
try {
str
= in
.readLine();
} catch (Exception e
) {
System
.out
.println(e
.getMessage());
}
return str
;
}
}
服务器端
import java
.net
.*
;
import java
.io
.*
;
public class ServerTest {
public static void main(String
[] args
) {
try {
ServerSocket server
= new ServerSocket(8001);
System
.out
.println("服务已建立于端口" + server
.getLocalPort());
while (true) {
Socket connection
= server
.accept();
System
.out
.println("连接已建立");
DataInputStream in
= new DataInputStream(connection
.getInputStream());
DataOutputStream out
= new DataOutputStream(connection
.getOutputStream());
String line
= "";
while (!line
.equalsIgnoreCase(".QUIT")) {
line
= in
.readUTF();
System
.out
.println("服务器接收数据:" + line
);
out
.writeUTF(line
);
}
in
.close();
out
.close();
connection
.close();
}
} catch (Exception e
) {
System
.out
.println(e
.getMessage());
}
}
}