标签:lin 创建 over soc love you 取ip地址 string case
该类用于封装一个ip地址,并提供了一系列与IP地址相关的方法
方法名 | 作用 |
---|---|
getByName(String) | 传递主机名以获得指定地址对象 |
getLocalHost() | 直接返回本地主机地址对象 |
getHostName() | 根据地址对象获取主机名 |
getHostAddress() | 根据地址对象获取ip地址 |
public static void main(String[] args) throws Exception {
InetAddress local = InetAddress.getLocalHost();
InetAddress remote = InetAddress.getByName("www.baidu.com");
System.out.println("本机的IP地址:" + local.getHostAddress());
System.out.println("IP地址:" + remote.getHostAddress());
System.out.println("主机名为:" + remote.getHostName()); }
属于面向无连接通信协议,消耗资源小,通信效率高,但不保证数据完整性
DatagramSocket socket = new DatagramSocket();
String str = "i love you";
// 把数据进行封装到数据报包中
DatagramPacket packet = new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("localhost"),6666);
socket.send(packet);
// 发送
socket.close();
DatagramSocket socket = new DatagramSocket(6666);
byte[] buff = new byte[100];
DatagramPacket packet = new DatagramPacket(buff, 100);
socket.receive(packet);
// 接受传来的数据包
System.out.println(new String(buff, 0, packet.getLength()));
属于面向连接的通信协议,在传输数据前先建立逻辑连接,提供了可靠无差错的数据传输
// 1.创建一个ServerSocket对象
ServerSocket serverSocket = new ServerSocket(8888);
// 2.调用accept()方法接受客户端请求
Socket socket = serverSocket.accept();
System.out.println("成功连接"+socket.getInetAddress().getHostAddress());
// 3.获取socket对象的输入输出流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
String line = null;
// 读取客户端传过来的数据
while ((line = br.readLine()) != null) {
if (line.equals("over")) {
break;
}
System.out.println(line);
pw.println(line.toUpperCase());
}
pw.close();
br.close();
socket.close();
System.out.println(socket.getInetAddress().getHostAddress() + "断开连接");
Socket socket = new Socket("127.0.0.1", 8888);
BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
String line = br.readLine();
// 获取键盘所输入的字符串
pw.println(line);
if (line.equals("over")) {
break;
}
// 获取服务端传过来的大写字符串
System.out.println(reader.readLine());
}
reader.close();
br.close();
pw.close();
socket.close();
这部分内容比较简单也不常用到,选择简单跳过
标签:lin 创建 over soc love you 取ip地址 string case
原文地址:https://www.cnblogs.com/zohnn/p/12817169.html