概述
- java是internet上的语言,它从语言级上提供了对网络应用程序的支持
- java提供网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在Java本机安装系统里,由JVM控制
- 直接或者间接的通过网络协议与其它计算机实现数据交换,进行通讯
网络通信要素
通信地址
- IP IntAddress类
- 端口号
端口号加IP地址组合得出一个网络套接字Socket
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class AddressTest {
@Test
public void client(){
Socket socket = null;
OutputStream os = null;
try {
InetAddress inet1 = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet1, 8080);
os = socket.getOutputStream();
os.write("我是客户端".getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
@Test
public void server(){
ServerSocket ss = null;
Socket accept = null;
InputStream is = null;
ByteArrayOutputStream bis = null;
try {
ss = new ServerSocket(8080);
accept = ss.accept();
is = accept.getInputStream();
bis = new ByteArrayOutputStream();
byte[] bytes = new byte[5];
int len;
while ((len=is.read(bytes)) !=-1){
bis.write(bytes,0,len);
}
System.out.println(bis.toString());
System.out.println(accept.getInetAddress().getHostAddress());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(ss!=null){
try {
ss.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(accept!=null){
try {
accept.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if(bis!=null){
try {
bis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
网络规则
- TCP/IP协议
- TCP协议使用前,必须建立TCP连接,形成传输数据通道
- 传输前采用三次握手方式,点对点非常可靠
- 在连接中可以进行大数据传输
- 传输完毕,需释放已建立的连接,效率低
- UDP协议
- 将数据,源,目的包装成数据包,不需要建立连接
- 每个数据包大小限制在64K内
- 发动不管对方是否准备好,也不管是否接收到,不可靠
- 可以广播发送
- 发送数据完成不用释放资源,开销小,速度快
import org.junit.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPTest {
@Test
// 发送端
public void sender(){
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
String str = "我是UDP方式发送的导弹";
byte[] bytes = str.getBytes();
InetAddress localHost = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(bytes, 0, bytes.length, localHost, 8080);
ds.send(dp);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(ds!=null){
ds.close();
}
}
}
@Test
// 接受端
public void receiver(){
DatagramSocket ds = null;
try {
ds = new DatagramSocket(8080);
byte[] bytes = new byte[100];
DatagramPacket dp = new DatagramPacket(bytes, 0, bytes.length);
ds.receive(dp);
System.out.println(new String(dp.getData(),0,dp.getLength()));
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(ds!=null){
ds.close();
}
}
}
}
URL类
- 统一资源定位符,它表示Internet上某一资源的位置
- <传输协议>://<主机>:<端口号>/<文件名>#片段名?参数列表
import org.junit.Test;
import java.net.MalformedURLException;
import java.net.URL;
public class URLTest {
@Test
public void test(){
URL url = null;
try {
url = new URL("http://localhost:8080/test/test.txt?text=123");
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
// 获取URL的协议名
System.out.println(url.getProtocol());
// http
// 获取URL的主机名
System.out.println(url.getHost());
// localhost
// 获取URL的端口号
System.out.println(url.getPort());
//8080
// 获取URL的文件路径
System.out.println(url.getPath());
// /test/test.txt
// 获取URL的文件名
System.out.println(url.getFile());
// /test/test.txt?text=123
// 获取URL的查询名
System.out.println(url.getQuery());
// text=123
}
}
多线程服务端
客户端可以在任意时刻发送请求,而服务端必须时刻准备为客服端的请求提供反馈文章来源地址https://www.toymoban.com/news/detail-628768.html
// 创建多线程服务处理
import java.io.*;
import java.net.Socket;
public class ServerThread extends Thread{
Socket s = null;
public ServerThread(Socket s){
this.s = s;
}
@Override
public void run() {
InputStream is = null;
ObjectInputStream ois = null;
OutputStream os = null;
DataOutputStream dos = null;
try {
is = s.getInputStream();
ois = new ObjectInputStream(is);
User user = (User) ois.readObject();
boolean flag = false;
if(user.getName().equals("xiaoming")&&user.getPsw().equals("123")){
flag = true;
}
os = s.getOutputStream();
dos = new DataOutputStream(os);
dos.writeBoolean(flag);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}finally {
try {
dos.close();
os.close();
ois.close();
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
// 服务端代码
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class testServe {
public static void main(String[] args) throws Exception {
System.out.println("服务端启动成功");
ServerSocket ss = new ServerSocket(8080);
int count = 0;
// 等待信息
while (true){
Socket s = ss.accept();
new ServerThread(s).start();
count++;
System.out.println("接收第"+count+"个信息,ID为"+s.getInetAddress());
}
}
}
// 客户端代码
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class TestClient {
public static void main(String[] args) throws Exception {
InetAddress inet1 = InetAddress.getByName("127.0.0.1");
Socket so = new Socket(inet1, 8080);
Scanner scanner = new Scanner(System.in);
System.out.println("输入账号");
String name = scanner.next();
System.out.println("输入密码");
String pws = scanner.next();
User user = new User(name,pws);
OutputStream os = so.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(user);
InputStream is = so.getInputStream();
DataInputStream dis = new DataInputStream(is);
boolean b = dis.readBoolean();
if(b){
System.out.println("成功");
}else {
System.out.println("失败");
}
dis.close();
is.close();
oos.close();
os.close();
so.close();
}
}
文章来源:https://www.toymoban.com/news/detail-628768.html
到了这里,关于java22-网络编程的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!