本帖最后由 小石姐姐 于 2018-6-8 09:23 编辑
1.网络通信的三要素:传输协议,IP地址,端口号.(IPv4:点分十进制表示法)
2.常见服务占用的端口号:
80: HTTP服务,443: HTTPS服务, 安全加密的HTTP,21: FTP服务, 文件传输
3.两种协议.UDP协议和TCP协议
UDP协议: 无连接的不可靠协议,数据传输大小限制为64K(一个包),不需要建立连接即可传输,
数据发送速度快,不管是否收到
TCP协议:需要建立连接,可靠,传输大小没有限制,传输速度慢
4.java.net.InetAddress类: 用于表示IP地址对象 (InetAddress的实例包含 IP 地址,还可能包含相应的主机名)
// 静态方法
static InetAddress getLocalHost(): 获取本机的InetAddress对象
static InetAddress getByName(String host): 根据主机名或IP的字符串获取主机的InetAddress对象
static InetAddress getByAddress(byte[] addr): 根据IP获取InetAddress对象
如: InetAddress.getByAddress(new byte[]{(byte)192, (byte)168, (byte)1, (byte)1});
// 成员方法
String getHostAddress(): 返回主机的IP地址
String getHostName(): 返回主机名
5.UDP协议发送数据的方式:
DatagramSocket ds=new DatagramSocket();随机分配端口号
DatagramSocket(int port): 创建DatagramSocket对象, 指定端口号
UDP发送数据
public class UDPSender {
public static void main(String[] args) throws IOException {
DatagramSocket sender = new DatagramSocket();
String s = "hello udp, im comming!";
byte[] bys = s.getBytes(); // 查询GBK编码表转换为数字
int length = bys.length;
InetAddress receiverIP = InetAddress.getByName("192.168.11.33");
int receiverPort = 8888;
DatagramPacket packet = new DatagramPacket(bys, length, receiverIP, receiverPort)
sender.send(packet);
sender.close();
}
}
UDP接收端
public class UDPReceiver {
public static void main(String[] args) throws IOException {
DatagramSocket receiver = new DatagramSocket(8888);
byte[] bys = new byte[1024];
DatagramPacket packet = new DatagramPacket(bys, bys.length);
System.out.println("接收端等待数据...");
receiver.receive(packet);
byte[] data = packet.getData();
int length = packet.getLength();
InetAddress senderIP = packet.getAddress();
int senderPort = packet.getPort();
System.out.println("[" + senderIP + ":" + senderPort + "]发来消息:" + new String(data, 0, length));
receiver.close();
}
}
TCP发送数据
public class TCPClient {
public static void main(String[] args) throws IOException {
// 创建客户端Socket对象, 同时指定要连接的服务端的IP地址和端口号. 注意: 在创建对象时就开始连接服务端了
Socket client = new Socket(InetAddress.getByName("192.168.11.33"), 10086);
OutputStream out = client.getOutputStream();
out.write("hello tcp!".getBytes());
client.close();
}
}
TCP接收数据
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(10086);
Socket client = server.accept();
InputStream in = client.getInputStream();
byte[] bys = new byte[1024];
int len;
len = in.read(bys);
String s = new String(bys, 0, len);
InetAddress clientIP= client.getInetAddress();
int clientPort = client.getPort();
System.out.println("[" + clientIP + ":" + clientPort + "]发来消息:" + s);
client.close();
server.close();
}
} |
|