概述
-
网络编程:TCP/UDP,C/S架构
vs
网页编程:JavaWeb,B/S架构 -
环境变量:
C:\windows\system32
内才可以ping baidu.com。
获取IP
127.0.0.1
,Canonical经典的
public class Test {
public static void main(String[] args) throws Exception{
//InetAddress的方法,类似Arrays.sort()
System.out.println(InetAddress.getByName("127.0.0.1"));// /127.0.0.1
//修改System32\drivers\etc\hosts没用
System.out.println(InetAddress.getByName("localhost"));// localhost/127.0.0.1
System.out.println(InetAddress.getLocalHost());// DESKTOP-Adair/10.15.137.179
System.out.println(InetAddress.getByName("www.baidu.com"));// www.baidu.com/39.156.66.14
}
}
端口port
- 程序的端口。0~65535(2^16)
- TCP/UDP :2*65535。TCP:80 &&UDP:80,同一类型端口不可相同
- 端口分类
- 服务器端:公有端口0~1023(2^10)。HTTP:80 HTTPS:443 FTP:21
- 服务器端:程序注册端口1024~49151。Tomcat8080 MySQL3306 Oracle1521
- 客户端:端口号49152~65535:暂时的动态私有,不可用
#cmd
netstat -ano //查看所有端口
netstat -ano|findstr "10809" //查看指定端口,先查询再带入
tasklist|findstr "8232" //查看指定端口的进程
- C:\Windows\System32\drivers\etc\hosts
- host-port
public class Test {
public static void main(String[] args) throws Exception{
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
System.out.println(inetSocketAddress.getHostName()); //第一个参数hostname
System.out.println(inetSocketAddress.getPort()); //第二个参数port
}
}
通信协议
- TCP:类与打电话。三次握手、四次挥手
- UDP:类与发短信。DDOS:洪水攻击
TCP通信
-
客户端步骤:连接
new Socket("127.0.0.1", 9999)
,得到socket的os发送消息。 -
服务器步骤:建立服务的端口ServerSocket,等待用户的连接accept,接受用户的消息
传送文字
- 客户端:
socket
→os
public class Test {
public static void main(String[] args) throws Exception{
Socket socket = new Socket("127.0.0.1", 9999);
OutputStream os = socket.getOutputStream();
os.write("我是发送方".getBytes());
os.close();
socket.close();
}
}
- 服务器:
serverSocket
→accept
→is
→(buffer)
→bos
public class Test2 {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9999);
Socket accept = serverSocket.accept();
InputStream is = accept.getInputStream();
ByteOutputStream bos = new ByteOutputStream();
int len;
byte[] buffer = new byte[1024];//is和bos缓冲区
while ((len=is.read(buffer))!=-1){
bos.write(buffer,0,len);
}
System.out.println(bos);
bos.close();
is.close();
accept.close();
serverSocket.close();
}
}
传送图片
- 客户端代码:
fis
→(buffer)
→socket.os
public class Test {
public static void main(String[] args) throws Exception{
FileInputStream fis = new FileInputStream("car.jpg");
Socket socket = new Socket("127.0.0.1", 9999);
OutputStream os = socket.getOutputStream();
int len;
byte[] buffer = new byte[1024];
while((len=fis.read(buffer))!=-1){
os.write(buffer,0,len);
}
socket.shutdownOutput();//切忌:要关输出,否则无法接受
//接受:服务器回复
ByteOutputStream bos = new ByteOutputStream();
InputStream is = socket.getInputStream();
int len2;
byte[] buffer2 = new byte[1024];
while ((len2 = is.read(buffer2))!=-1){
bos.write(buffer2,0,len2);
}
System.out.println(bos);
bos.close();
//接受完成
os.close();
socket.close();
}
}
#socket.shutdownOutput();
- 服务器代码
public class Test2 {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9999);
Socket accept = serverSocket.accept();
InputStream is = accept.getInputStream();
FileOutputStream fos = new FileOutputStream("x.jpg");
int len;
byte[] bytes = new byte[1024];
while ((len=is.read(bytes))!=-1){
fos.write(bytes,0,len);
}
System.out.println(fos);//java.io.FileOutputStream@74a14482。可以忽略
//发送给:客户端消息
OutputStream os = accept.getOutputStream();
os.write("接受完成".getBytes());
os.close();
//发送文字结束
fos.close();
is.close();
accept.close();
serverSocket.close();
}
}
Tomcat服务器
tomcat是jsp(java编写)网站的服务器之一,就像asp网站要用到微软的IIS服务器,php网站用apache服务器一样,
jsp需要tomcat去解释。如果是hmtl浏览器即可查看效果。.jsp .asp .php 等浏览器无法解释了,需要特定服务器
- apache-tomcat-9.0.58解压包中bin,startup.bat。
- 运行tomcat。地址栏localhost:8080,
- webapps\ROOT中的index.jsp源码(html),
- ideal(8080)不可同Tomcat(8080)同时运行
- conf\logging.properties中ConsoleHandler.encoding = GBK
UDP
- 发送端:这次是发送包
DatagramSocket()
。之前通信TCP是I/O流Socket
,ServerSocket
public class Test {
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket();
String msg = "你好";
//packet有数据和目的地。故socket直接发送即可
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, InetAddress.getByName("localhost"), 8888);
socket.send(packet);
socket.close();
}
}
- 接受端:一锅老鼠屎
import com.sun.org.apache.xpath.internal.operations.String;
不可运行
public class Test2 {
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket(8888);
byte[] buffer = new byte[1024];
//设置packet的大小buffer即可
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}
UDP通信
单工
- 发送端:
new BufferedReader(new InputStreamReader(System.in))
public class Test {
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet;
while (true){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
packet = new DatagramPacket(s.getBytes(),0,s.getBytes().length,InetAddress.getByName("localhost"),7777);
socket.send(packet);
}
}
}
- 接受端
public class Test2 {
public static void main(String[] args) throws Exception{
DatagramSocket socket = new DatagramSocket(7777);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
while (true){
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getData().length));
}
}
}
利用线程
- 发送线程
public class Test implements Runnable{
private String toIP;
private int port;
public Test(String toIP, int port){
this.toIP = toIP;
this.port = port;
}
@Override
public void run() {
while (true){
try {
DatagramSocket socket = new DatagramSocket();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
DatagramPacket packet = new DatagramPacket(s.getBytes(), 0, s.getBytes().length, InetAddress.getByName(toIP), port);
socket.send(packet);
}catch (Exception e){ }
}
}
}
- 接受线程
public class Test2 implements Runnable{
private int port;
private String fromname;
public Test2(int port,String fromname) {
this.port = port;
this.fromname = fromname;
}
@Override
public void run() {
while (true){
try{
DatagramSocket socket = new DatagramSocket(port);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
System.out.println(this.fromname+":"+new String(packet.getData(), 0, packet.getData().length));
}catch (Exception e){ }
}
}
}
- 老师
public class Teacher {
public static void main(String[] args) {
new Thread(new Test("localhost",9999)).start();//老师发话
new Thread(new Test2(8888,"student")).start();//老师收听
}
}
- 学生
public class Student {
public static void main(String[] args) {
new Thread(new Test2(9999,"teacher")).start();//同学收听
new Thread(new Test("localhost",8888)).start();//同学发话
}
}
URL
协议://ip地址:端口/项目名/资源
- 格式
public class URLDemo01 {
public static void main(String[] args) throws Exception{
URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=adair&password=123");
System.out.println(url.getProtocol());//协议
System.out.println(url.getHost());//IP
System.out.println(url.getPort());//Port
System.out.println(url.getPath());//路径
System.out.println(url.getFile());//全路径
System.out.println(url.getQuery());//参数
}
}
- 从tomcat中加载文件资源:
url
→urlconnection
→is
→(buffer)
→fos
public class Test {
public static void main(String[] args) throws Exception{
URL url = new URL("http://localhost:8080/adair/play.txt");
HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("SecurityFile2.txt");
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
urlConnection.disconnect();
}
}
- 下载网上的资源,同上
public class Test {
public static void main(String[] args) throws Exception{
URL url = new URL("https://m10.music.126.net/20220408143139/42619cfcc99dc6ba23ca2815a8c60036/ymusic/0f5c/060b/560c/86d0abcd291a054b67fcafbe794c0825.mp3");
HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("6.mp3");
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
urlConnection.disconnect();
}
}