Java网络编程

InetAddress类

InetAddress类的中未提供公开的构造方法,因此无法直接new对象;其常用静态方法如下:

  1. getLocalHost() 获取本地主机对象
  2. getByName(String host) 根据主机名(或ip)获取InetAddress对象
  3. getByAddress(byte[] b) 根据字节数组获取InetAddress对象
  4. getByAddress(String host,byte[] b) 根据主机名称和ip的字节数组获取InetAddress对象
public class InetAddressDemo {

	public static void main(String[] args) throws UnknownHostException {
		
		//获取本地主机对象  localhost
		InetAddress ip = InetAddress.getLocalHost();
		System.out.println(ip);
		//获取主机名(计算名)
		System.out.println(ip.getHostName());
		//获取主机地址(ip)
		System.out.println(ip.getHostAddress());
		
		//获取回送地址
		System.out.println(InetAddress.getLoopbackAddress());
		
		ip = InetAddress.getByName("mrchai");
		System.out.println(ip);
		
		byte[] b = new byte[]{(byte)192,(byte)168,(byte)0,(byte)198};
		ip = InetAddress.getByAddress(b);
		System.out.println(ip);
		
		ip = InetAddress.getByAddress("mrchai", b);
		System.out.println(ip);
	}
}

Socket通信

Socket(套接字)是主机中ip和端口结合,通过Socket可以轻松实现不同主机之间应用程序的通信,可以通俗的理解为不同主机中相同软件的的通信桥梁,关于计算机应用的通信模式分为以下两种:

  1. C/S架构:客户端(Client)/服务端(Server)模式。
  2. B/S架构:浏览器(Browser)/服务器(Server)模式。
服务端
public class MyServer {

	public static void main(String[] args) throws IOException {
		
		
//		ServerSocket server = new ServerSocket();
//		server.bind(new InetSocketAddress(8888));
		
		//占据8888端口创建一个服务 192.168.4.198
		ServerSocket server = new ServerSocket(8888);
		System.out.println("服务已创建,等待连接...");
		
		//循环监听
		while(true){
			//开始监听,一旦客户端连接则返回Socket对象
			Socket s = server.accept();
			System.out.println("客户端已连接!"+s.getInetAddress());
			
			//获取Socket的输出流
			OutputStream os = s.getOutputStream();
			//将字节输出流包装为打印流
			PrintWriter pw = new PrintWriter(os);
			pw.println("欢迎使用SOFTEEM不知道干啥的服务器。。。");
			pw.flush();
			pw.close();
		}
		
	}
}
客户端
public class MyClient {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		//连接到指定ip,指定端口的服务
		Socket s = new Socket("192.168.4.198",8888);
		//获取基于Socket的字节输入流
		InputStream is = s.getInputStream();
		//将字节流转换为字符流
		InputStreamReader isr = new InputStreamReader(is);
		//将低级字符流转换为缓冲流
		BufferedReader br = new BufferedReader(isr);
		String msg = br.readLine();
		System.out.println(msg);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值