文章目录
- 一、网络编程简介
- 二、端口
- 三、建立Tcp连接传数据
- 四、Tcp实现文件上传
- 五、Tomcat
- 六、UDP
- 七、UDP实现实时聊天
- 八、URL申请资源
一、网络编程简介
package SocketChap;
import java.net.InetAddress;
import java.net.UnknownHostException;
/*
编程的目的是
传播交流信息、数据交换、通信
想要达到对应的效果
1、通过ip:端口号,定位到这个计算机上的某个资源
2、找到了这个主机,如何传输数据?
网络通信的要素
通信双方的地址
ip+端口 定位到电脑上的某个应用
规则
网络通信的协议
IP地址 inetAddress
唯一定位一台网络上计算机
127.0.0.1 本机的localhost
*/
public class Demo1 {
public static void main(String[] args) {
try {
// 查询网站ip地址
InetAddress byName = InetAddress.getByName("www.baidu.com");
System.out.println(byName);
// 查询本机地址
InetAddress InetAddress1 = InetAddress.getByName("127.0.0.1");
InetAddress InetAddress2 = InetAddress.getByName("localhost");
InetAddress InetAddress3 = InetAddress.getLocalHost();
System.out.println(InetAddress1);
System.out.println(InetAddress2);
System.out.println(InetAddress3);
// 常用方法
System.out.println(InetAddress2.getCanonicalHostName());//规范的名字
System.out.println(InetAddress2.getHostAddress());//ip
System.out.println(InetAddress2.getHostName());//域名,或者自己的电脑名字
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
二、端口
/*
端口表示一个计算机上程序的进程
不同进程有不同的端口号,用来区分软件
端口固定0-65535
分为TCP端口和UDP端口 单个协议下端口不冲突
端口分类
共有端口0-1023
程序注册端口2014-49151,分配给用户或者程序
Tomcat 8080
Mysql 3306
Oracle 1521
动态、私有端口 49152-65535
netstat -ano 查看所有的端口
netstat -ano[findstr "5900"] 查看指定的端口
tasklist|findstr "8696" 查看指定端口的进程
*/
package SocketChap;
import java.net.InetSocketAddress;
public class SockerDemo {
public static void main(String[] args) {
InetSocketAddress SocketAddress = new InetSocketAddress("localhost", 8080);
System.out.println(SocketAddress.toString());
System.out.println(SocketAddress.getAddress());
System.out.println(SocketAddress.getHostName());
System.out.println(SocketAddress.getPort());
}
}
三、建立Tcp连接传数据
/*
客户端
连接服务器socket
发送消息
服务器
建立服务的端口 Seversocket
等待用户的连接 accept
接收用的消息
*/
package SocketChap;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SeverDemo1 {
public static void main(String[] args) throws IOException {
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//获得socket对象 并且设置对应的端口号
ServerSocket serverSocket=new ServerSocket(9999);
//监听客户端的请求
socket=serverSocket.accept();
//从socket中获取输出流
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) {
throw new RuntimeException(e);
}finally {
baos.close();
is.close();
socket.close();
}
}
}
package SocketChap;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
public class ClientDemo1 {
public static void main(String[] args) throws IOException {
Socket socket=null;
OutputStream os=null;
try {
InetAddress inetAddress=Inet4Address.getByName("127.0.0.1");
int port=9999;
//按照ip地址和端口号连接对应的服务器
socket=new Socket(inetAddress,port);
//把数据写到soket输出流中 传出去
os=socket.getOutputStream();
os.write("Hello".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
os.close();
socket.close();
}
}
}
四、Tcp实现文件上传
package SocketChap;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class ClientDemo2 {
public static void main(String[] args) throws Exception {
Socket socket=null;
OutputStream os=null;
FileInputStream fis=null;
InputStream inputStream=null;
ByteArrayOutputStream baos=null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 9998);
os=socket.getOutputStream();
fis=new FileInputStream(new File("img1.jpg"));
byte[] buffer=new byte[1024];
int len;
while ((len=fis.read(buffer))!=-1){
os.write(buffer ,0,len);
}
// 告诉服务器已经结束
socket.shutdownOutput();
// 确定服务器接受完毕,才可以断开连接
inputStream = socket.getInputStream();
baos=new ByteArrayOutputStream();
byte[] buffer2=new byte[1024];
int len2;
while ((len2=inputStream.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
inputStream.close();
baos.close();
fis.close();
os.close();
socket.close();
}
}
}
package SocketChap;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SeverDemo2 {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket=null;
FileOutputStream fos=null;
InputStream is=null;
Socket socket=null;
try {
serverSocket=new ServerSocket(9998);
socket = serverSocket.accept();
is=socket.getInputStream();
fos=new FileOutputStream(new File("recive.jpg"));
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
// 通知客户端接受完毕
OutputStream os1=socket.getOutputStream();
os1.write("接受完毕".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
is.close();
fos.close();
socket.close();
serverSocket.close();
}
}
}
五、Tomcat
服务端
自定义S
Tomcat服务器S
客户端
自定义S
浏览器B
六、UDP
package SocketChap;
import java.net.*;
//发送端
// 不需要简历服务器
public class UDPClient {
public static void main(String[] args) throws Exception{
// 建立一个socket
DatagramSocket datagramSocket = new DatagramSocket();
// 建立一个包
String msg="Hello 服务器";
InetAddress inetAddress=InetAddress.getByName("localhost");
int port=9090;
// 数据 数据的长度起始 要发送给谁
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,inetAddress,port);
// 发送包
datagramSocket.send(datagramPacket);
// 关闭流
datagramSocket.close();
}
}
package SocketChap;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
//接收端
//还是要等待客户端的连接
public class UDPSever {
public static void main(String[] args) throws Exception {
// 开放端口
DatagramSocket socket=new DatagramSocket(9090);
// 接受数据包
byte[] buffer = new byte[1024];
// 接收
DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
// 关闭连接
socket.close();
}
}
七、UDP实现实时聊天
package SocketChap.UDP3;
public class TalkStudent {
public static void main(String[] args) {
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"老师")).start();
}
}
package SocketChap.UDP3;
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(5555,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"老师")).start();
}
}
package SocketChap.UDP3;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable{
DatagramSocket socke=null;
private int port;
private String msgfrom;
public TalkReceive(int port,String msgfrom) {
this.port = port;
this.msgfrom=msgfrom;
try {
socket=new DatagramSocket(port);
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
DatagramSocket socket=null;
@Override
public void run() {
while (true){
try {
// 准备接收包裹
byte[] container = new byte[1024];
DatagramPacket packet=new DatagramPacket(container,0,container.length);
socket.receive(packet);
// 断开连接
byte[] data=packet.getData();
String receiveData = new String(data, 0,packet.getLength());
System.out.println(msgfrom+receiveData);
if (receiveData.equals("bye")){
break;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
package SocketChap.UDP3;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class TalkSend implements Runnable{
DatagramSocket socket=null;
BufferedReader reader=null;
DatagramPacket packet=null;
private int fromPort;
private String toIp;
private int toPort;
public TalkSend(int fromPort, String toIp, int toPort) {
this.fromPort = fromPort;
this.toIp = toIp;
this.toPort = toPort;
try {
socket=new DatagramSocket(fromPort);
reader=new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
@Override
public void run() {
while (true){
try {
String data=reader.readLine();
byte[] datas = data.getBytes();
packet=new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIp,this.toPort));
socket.send(packet);
if (data.equals("bye")){
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
socket.close();
}
}
八、URL申请资源
package SocketChap.URL1;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Demo1 {
public static void main(String[] args) throws IOException {
// 下载地址
URL url = new URL("http://localhost:8080/fly/mydata.txt");
System.out.println(url.getProtocol());
System.out.println(url.getHost());
System.out.println(url.getPort());
System.out.println(url.getPath());
System.out.println(url.getFile());
System.out.println(url.getQuery());
// 连接到这个资源 HTTP
HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
InputStream is=urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("mydata.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();
}
}