网络编程
软件架构
CS:Client/Server
BS:Browser/Server
网络通信协议
所有的计算机都是处于网络中的,计算机通信时需要遵守一定的规则,这种规则叫做网络通信协议
常见的协议
https ,http,ftp,ip,tcp,udp
tcp/ip四层
链路层 ——网络层——传输层——应用层
ip(internet Protocol)
是由四组数字组成的网络中的计算机的唯一标识,每组数字之间使用逗号隔开。
端口号
计算机中的每一个应用程序都有一个对应的数字,用来标识该应用程序。1-1024端口已经被占用,不能使用。
tcp协议(三次握手)
1.发送端向接收端发送建立连接的请求。
2.接收端给发送端回复,表示收到请求可以建立连接
3.发送端向接收端发送确认请求
Socket通信的代码实现
public abstract class Test{
public static void main(String[] args) throws IOException {
//创建ServerSocket对象,指定端口号
ServerSocket ss = new ServerSocket(6666);
//接受连接,返回Socket对象
Socket accept = ss.accept();
//获取输入流
InputStream is = accept.getInputStream();
byte[] b = new byte[1024];
//接收数据
int len = is.read(b);
String str = new String(b,0,len);
//打印
String address = accept.getInetAddress().getHostAddress();
System.out.println(str+"--"+address);
}
}
public class Send{
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
//创建一个Socket对象,指定ip和端口号
Socket socket = new Socket("192.168.19.1",6666);
//通过socket得到输出流
OutputStream os = socket.getOutputStream();
System.out.println("请输入一句话");
String str = input.next();
os.write(str.getBytes());
}
}