网络编程
IP 端口号
网络通信协议:TCP/IP
小结:
1.网络编程中有两个主要的问题
如何准确的定位到网络上的一台或多台主机
找到主机之后如何进行通信
2.网络编程中的要素
IP和端口号 IP
网络通信协议 TCP/UDP
1.IP
1.1 ip地址:InetAddress
127.0.0.1 本机 localhost
ipv4/ipv6
*ipv4 4个字节 127.0.0.1
ipv6 128位。8个无符号整数(7个点)
公网(互联网)-私网(局域网)
ABCD类地址
192.168.xx.xx 组织内部使用的
域名
1.2 端口
不用的进程有不同的端口号
被规定0-65536
TCP/UDP:65535*2 单个协议下端口不能冲突
端口分类:
公用端口:0-1023
程序注册端口:1024-49151
tomcat:8080 MySQL3306 Oracle1521
动态、私有:49152-65535
netstat -ano //查看所有的端口
netstat -ano|findstr"5900" //查看指定端口
tasklist|findstr"8696" //查看指定端口的进程
1.3 通信协议
协议即是约定
TCP/IP
TCP:用户传输协议
UDP:用户数据报协议
IP:网络互连协议
TCP和UDP对比
TCP:打电话
三次握手,四次挥手
客户端、服务端
传输完成、释放连接,效率低
UDP:发短信
//客户端
public static void main(String[] args) {
InetAddress serverIP = null;
OutputStream os = null;
Socket socket = null;
try {
// 要知道这个地址
serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
// 创建一个socket连接
socket = new Socket(serverIP, port);
// 发送消息 io流
os = socket.getOutputStream();
os.write("你好!".getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
if (socket != null) {
try {
socket.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
客户端、服务端没有明确的界限
不管有没有准备好,都可以发送
1.4 TCP
//服务端
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
// 提供一个地址
serverSocket = new ServerSocket(9999);
while (true) {
// 等待客户端连接过来
socket = serverSocket.accept();
// 读取客户端的消息
is = socket.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}