java 网络编程
来源:互联网 发布:淘宝子账号有哪些权限 编辑:程序博客网 时间:2024/06/18 18:19
package org.example.network;import java.net.InetAddress;/** * * DOC InetAddress类的使用<br/> * 该类的功能是代表一个IP地址,并且将IP地址和域名相关的操作方法包含在该类的内部 常用的功能->获取ip地址 */public class Main1 { public static void main(String[] args) throws Exception { // 使用域名创建对象 InetAddress inet1 = InetAddress.getByName("www.baidu.com"); // 使用IP地址创建对象 InetAddress inet2 = InetAddress.getByName("127.0.0.1"); // 获取本机地址对象 InetAddress inet3 = InetAddress.getLocalHost(); String hostName = inet3.getHostName(); String ip = inet3.getHostAddress(); System.out.println("inet1--->" + inet1); System.out.println("inet2--->" + inet2); System.out.println("inet3--->" + inet3); System.out.println("inet3--hostName->" + hostName); System.out.println("inet3--ip->" + ip); // test results: /** * inet1--->www.baidu.com/220.181.112.143 <br/> * inet2--->/127.0.0.1 <br/> * inet3--->yzb-PC/192.168.1.132 <br/> * inet3--hostName->yzb-PC <br/> * inet3--hostAddress->192.168.1.132 */ }}
package org.example.network;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;/** * * DOC TCP编程<br/> * TCP就像打电话一样,流程是:<br/> * 客户端:建立连接-》交换数据-》释放连接<br/> * 服务器端:监听端口-》建立连接-》交换数据-》施放连接 * */public class Main2 { public static void main(String[] args) { Main2 main = new Main2(); // main.new Server().startServer(); main.new Client().request(); } /** * DOC 客户端 * */ public class Client { public void request() { Socket socket = null; OutputStream out = null; InputStream in = null; String ip = "127.0.0.1";// 要连接的ip地址 int port = 9090;// 要连接的端口号 String data = "hello server.";// 要发送的内容 try { // 建立连接 socket = new Socket(ip, port); // 获得输出流 out = socket.getOutputStream(); // 发送消息 out.write(data.getBytes()); // 获取输入流 in = socket.getInputStream(); byte bb[] = new byte[1024]; // 获取反应信息 int n = in.read(bb); System.out.println("client端获取的反馈信息:" + new String(bb, 0, n)); } catch (Exception e) { e.printStackTrace(); } finally { try { // 关闭连接 in.close(); out.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } } } public class Server { public void startServer() { ServerSocket serverSocket = null; Socket socket = null; InputStream in = null; OutputStream out = null; int port = 9090;// 监听的端口号 try { // 启动服务,监听端口号 serverSocket = new ServerSocket(port); // 该操作会阻塞线程,直到获取到一个请求,才会往下走 socket = serverSocket.accept(); // 获取输入的信息 in = socket.getInputStream(); byte bb[] = new byte[1024]; int n = in.read(bb); System.out.println("服务器端收到的内容:" + new String(bb, 0, n)); // 反馈信息 out = socket.getOutputStream(); out.write("hello .".getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); in.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }}