网络编程
网络分层
由于结点之间联系很复杂,在制定协议时,把复杂成份分解成一些简单的成份,再将它们复合起来。最常用的复合方式是层次方式,即同层间可以通信、上一层可以调用下一层,而与再下一层不发生关系。
端口
端口是虚拟的概念,并不是说在主机上真的有若干个端口。通过端口,可以在一个主机上运行多个网络应用程序。可以类比为:IP 相当于公司,端口相当于公司各部门,URL,相当于各部门的人员
//1) 、获取对象InetSocketAddress(Stringhostname, intport)
InetSocketAddress(InetAddressaddr, intport)
//2) 、方法
getAddress() //返回 InetAddress 对象
getPort() //返回端口
getHostName() //返回域名
URL
URL全称是Uniform Resource Location,也就是统一资源位置。实际上,URL就是一种特殊的URI,它除了标识一个资源,还会为资源提供一个特定的网络位置,客户端可以通过它来获取URL对应的资源。
protocol://userInfo@host:port/path?query#fragment 协议://用户信息@主机名:端口/路径?查询#锚点
协议
TCP:TCP(transfer control protocol) 打电话面向连接、安全、可靠,效率低UDP:UDP(UserDatagramProtocol ) 发送短信非面向连接、不安全、数据可能丢失、效率高
UDP
UserDatagramProtocol,一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务。其特点为:非面向连接;传输不可靠;数据可能丢失。
服务端示例
public class Server {
public static void main(String
[] args
) throwsException
{
DatagramSocket ds
=new DatagramSocket(8999);
byte[] b
=new byte[1024];
DatagramPacket dp
=new DatagramPacket(b
,b
.length
);
ds
.receive(dp
);
String string
= new String(dp
.getData(),0,dp
.getLength());
System
.out
.println(string
);
ds
.close();
}
}
客户端示例
public class Client {
public static void main(String
[] args
) throwsException
{
DatagramSocket ds
= new DatagramSocket(9000);
byte[] b
="aaaa".getBytes();
DatagramPacket dp
= new DatagramPacket(b
,b
.length
,newInetSocketAddress("localhost",8999));
ds
.send(dp
);
ds
.close(); }}
TCP
服务器端示例
import java
.io
.BufferedInputStream
;
import java
.io
.DataInputStream
;
import java
.io
.IOException
;
import java
.net
.ServerSocket
;
import java
.net
.Socket
;
public class TCPServer02 {
public static void main(String
[] args
) throws Exception
{
ServerSocket server
= new ServerSocket(9999);
System
.out
.println("--------------Server-----------------");
Socket client
= server
.accept();
System
.out
.println("一个客户端已经连接成功....");
DataInputStream is
= new DataInputStream(new BufferedInputStream(client
.getInputStream()));
String msg
= is
.readUTF();
System
.out
.println(msg
);
is
.close();
client
.close();
server
.close();
}
}
客户端示例
import java
.io
.*
;
import java
.net
.Socket
;
public class TCPClient01 {
public static void main(String
[] args
) throws Exception
{
Socket client
= new Socket("localhost",9999);
System
.out
.println("------------------Client--------------");
DataOutputStream os
= new DataOutputStream(new BufferedOutputStream(client
.getOutputStream()));
os
.writeUTF("哈哈哈");
os
.flush();
os
.close();
client
.close();
}
}