网络程序设计(中)

TCP程序设计基础

TCP程序设计是指利用Socket类编写通信程序,TCP协议进行通信的两个应用程序一个称为服务器,另一个称为客户机。
在这里插入图片描述
InetAddress类
java.net包中的InetAddress类是与IP地址相关的类。
InetAddress类的常用方法:

						返回值类型
getByName(string x)		InetAddress		获取Host相对应的InetAddress对象
getHostAddress()		string			获取InetAddress对象所包含的ip对象
getHostName()			string			获取此ip地址的主机名
getLocalHost()			InetAddress		返回主机的InetAddress对象

实例 使用获取此ip地址的主机名、获取InetAddress对象所包含的ip对象

import java.net.InetAddress;
import java.net.UnknownHostException;

public class inetaddress {
	public static void main(String[] args) {
		InetAddress ip;
		try {
			ip=InetAddress.getLocalHost();
				System.out.println("本机name:"+ip.getHostName());
		System.out.println("本机ip地址:"+ip.getHostAddress());	
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//实例化

	}
}

InetAddress类的方法会抛出UnkonwKostException异常,所以必须进行异常处理。
在这里插入图片描述
ServerSocket类
ServerSocket类用于表示服务器套接字,主要功能是等待来自网络上的"请求",可以通过指定的端口来等待连接的套接字。
在这里插入图片描述
ServerSocket类的常用方法
在这里插入图片描述

发布了58 篇原创文章 · 获赞 7 · 访问量 6357

猜你喜欢

转载自blog.csdn.net/m0_46193982/article/details/105030995