文章目录
- TCP和UDP
- TCP协议
- UDP协议
- InetAddress 类
- Socket通信
- 案例
java.net 包下使用的网络
IP地址使用4个字节 32位
一个字节的范围 0~255
ipv6 16个字节 128位
TCP和UDP
TCP协议
1、使用tcp协议前 必须先建立TCP连接 形成传输数据通道
2、传输前 采用三次握手的方式 可靠的
3、TCP协议进行通信的过长城应用进程:客户端 服务端
4、连接中 可以进行大数据量的传输
5、传输完毕 需释放已建立的连接 效率低
UDP协议
1、将数据、源、目的封装数据包 不需要建立连接
2、每个数据报的大小限制在64k内
3、因无需连接 故不可靠
4、发送的数据结束时 无释放资源 因为不是面向连接的 速度快
InetAddress 类
相关方法
1、获取本机InetAddress 对象 getLocalHost
2、根据指定主机名 / 域名获取ip地址对象getByName
3、获取InetAddress 对象的主机名 getHostName
4、获取InetAddress 对象的地址getHostAddress
也是序列化的对象
public static void main(String[] args) throws UnknownHostException {
//1、获取本机的InetAddress对现象
InetAddress localhost = InetAddress.getLocalHost();
System.out.println(localhost);
//2、 根据指定的主机名获取InetAddress 对象
InetAddress host1 = InetAddress.getByName("");
System.out.println(host1);
//3、根据返回InetAddress对象 比如百度对应的wwww.baidu.com对应的
InetAddress host2 = InetAddress.getByName("www.baidu.com");
System.out.println("host2="+host2;
//4、通过InetAddress 对象 获取对应的地址
String hosrAddress = host2.getHostAddress();
//5、通过InetAddress 对象 获取对应的主机名 或者域名
String hostName = host2.getHostName();
}
Socket通信
1、套节字开发 广泛应用与应用程序
2、通信的两端都需要有Socket 是两台机器之间通信的端点
3、网络通信 其实就是Socket间的通信
4、socket 允许程序把网络当成一个流 数据在两个socket之间通过IO传输
4、一般主动发起通信的应用沉痼属于客户端 等待通信请求的为服务端
案例
java"> public static void main(String[] args) throws Exception {
//1、服务器在本机监听8888端口
ServerSocket serverSocket = new ServerSocket(8888);
//2、等待连接
Socket socket = serverSocket.accept();
//3、读取客户端发送的数据
///通过socket得到输入的流
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] bytes = StreamUtils.streamToByteArray(bis);
String destfilepath = "";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destfilepath));
bos.write(bytes);
//关闭流
bos.close();;
bis.close();
socket.close();
serverSocket.close();
}
java">public class StreamUtils {
public static byte[] streamToByteArray(InputStream is) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len;
while ((len=is.read(b))!=-1){
bos.write(b,0,len);
}
byte[] array = bos.toByteArray();
bos.close();
return array;
}
}
java">public class demo4 {
public static void main(String[] args) throws Exception {
//创建客户端连接服务器 得到socket对象
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//创建读取磁盘文件的输入流
String filepath = "";
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(""));
//bytes就是filePath对应的字节数组
byte[] bytes = StreamUtils.streamToByteArray(bis);
//通过socket获取到输出流 将bytes数据发送给服务端
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(bytes); //将文件对应的字节数组的内容写入到数据通道中
bis.close();
socket.shutdownOutput(); //设置写入数据的结束标志
//关闭相对应的流
bos.close();
socket.close();
}
}