标签:服务端 date com xxx rgs 条件 down writer imp
Java中封装IP地址的类:InetAddress
。
package org.westos.demo;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author lwj
* @date 2020/6/13 9:23
*/
public class MyTest {
public static void main(String[] args) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName("LAPTOP-SFH5B12N");
System.out.println(inetAddress);
//LAPTOP-SFH5B12N/192.168.137.1
System.out.println(inetAddress.getHostAddress());
//192.168.137.1
System.out.println(inetAddress.getHostName());
//LAPTOP-SFH5B12N
InetAddress address = InetAddress.getByName("192.168.137.1");
System.out.println(address);
///192.168.137.1
System.out.println(address.getHostAddress());
//192.168.137.1
System.out.println(address.getHostName());
//LAPTOP-SFH5B12N.mshome.net
System.out.println(InetAddress.getLocalHost());
//LAPTOP-SFH5B12N/192.168.137.1
}
}
Socket = IP + 端口号。
UDP协议的特点:通信两端不需要建立连接,发送的数据大小有限制,因为不需要建立连接,效率高一些,但是属于不可靠协议,有可能会发生数据丢失问题
通信两端都要有Socket,针对不同协议,Java为我们封装了不同的Socket。
UDP:DatagramSocket
和 DatagramPacket
。
基本的UDP通信代码
Client:发送数据方
package org.westos.demo2;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* @author lwj
* @date 2020/6/13 9:39
*/
public class UDPClient {
public static void main(String[] args) throws IOException {
//1、创建UDP的Socket
DatagramSocket socket = new DatagramSocket();
//2、封装数据
String data = "起床了";
System.out.println(data.getBytes().length);
//9
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.getBytes().length, InetAddress.getLocalHost(), 8888);
socket.send(packet);
//3、释放资源
socket.close();
}
}
Server:接收数据方
package org.westos.demo2;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Arrays;
/**
* @author lwj
* @date 2020/6/13 9:49
*/
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(8888);
byte[] bytes = new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
socket.receive(packet);
//等待接收数据,是一个阻塞方法
byte[] data = packet.getData();
System.out.println(Arrays.toString(data));
//[-24, -75, -73, -27, -70, -118, -28, -70, -122, 0, ...]
int length = packet.getLength();
System.out.println(length);
//9
String hostAddress = packet.getAddress().getHostAddress();
int port = packet.getPort();
String s = new String(data, 0, length);
System.out.println(hostAddress + "从" + port + "端口" + "给你发来消息:" + s);
//192.168.137.1从49832端口给你发来消息:起床了
socket.close();
}
}
A电脑
package org.westos.demo3;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
/**
* @author lwj
* @date 2020/6/13 11:11
*/
public class AComputer {
public static void main(String[] args) throws SocketException {
//开启子线程接收B发来的消息
new Thread(()->{
try {
DatagramSocket datagramSocket = new DatagramSocket(9999);
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
while (true) {
//接收消息的动作是需要循环的
datagramSocket.receive(datagramPacket);
byte[] data = datagramPacket.getData();
int length = datagramPacket.getLength();
String hostAddress = datagramPacket.getAddress().getHostAddress();
int port = datagramPacket.getPort();
String msg = new String(data, 0, length);
System.out.println("收到" + hostAddress + ":" + port + "发送的消息:" + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
//主线程给B电脑发送消息
DatagramSocket datagramSocket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true) {
try {
byte[] bytes = sc.next().getBytes();
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 7777);
datagramSocket.send(datagramPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
B电脑
package org.westos.demo3;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
/**
* @author lwj
* @date 2020/6/13 11:12
*/
public class BComputer {
public static void main(String[] args) throws SocketException {
//开启子线程接收A电脑发送的数据
new Thread(()->{
try {
DatagramSocket datagramSocket = new DatagramSocket(7777);
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
while (true) {
//接收消息的动作是需要循环的
datagramSocket.receive(datagramPacket);
byte[] data = datagramPacket.getData();
int length = datagramPacket.getLength();
String hostAddress = datagramPacket.getAddress().getHostAddress();
int port = datagramPacket.getPort();
String msg = new String(data, 0, length);
System.out.println("收到" + hostAddress + ":" + port + "发送的消息:" + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
//主线程给A发送消息
DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true) {
try {
byte[] bytes = sc.next().getBytes();
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9999);
socket.send(datagramPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
测试:
B电脑
在吗?
收到192.168.137.1:64829发送的消息:在呢,怎么了
想问问你有没有时间出来玩?
收到192.168.137.1:64829发送的消息:有啊,和谁?去哪?
我和我哥,去xxx
收到192.168.137.1:64829发送的消息:可以啊
ok,那你准备一下
收到192.168.137.1:64829发送的消息:ok
A电脑
收到192.168.137.1:57291发送的消息:在吗?
在呢,怎么了
收到192.168.137.1:57291发送的消息:想问问你有没有时间出来玩?
有啊,和谁?去哪?
收到192.168.137.1:57291发送的消息:我和我哥,去xxx
可以啊
收到192.168.137.1:57291发送的消息:ok,那你准备一下
ok
都是UDP协议下的开放的端口。
package org.westos.demo4;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author lwj
* @date 2020/6/13 13:35
*/
public class Client {
public static void main(String[] args) throws IOException {
//TCP:通信两端需要建立连接,属于可靠协议
//TCP客户端:Socket
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//Socket(InetAddress address, int port)
//获取通道中的流
OutputStream outputStream = socket.getOutputStream();
byte[] bytes = "你好TCP,我来了".getBytes();
outputStream.write(bytes);
//接收服务端的反馈
InputStream inputStream = socket.getInputStream();
byte[] bytes1 = new byte[1024];
int read = inputStream.read(bytes1);
String msg = new String(bytes1, 0, read);
System.out.println("收到服务器的反馈:" + msg);
//收到服务器的反馈:收到~
socket.close();
}
}
package org.westos.demo4;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author lwj
* @date 2020/6/13 13:43
*/
public class Server {
public static void main(String[] args) throws IOException {
//服务端的Socket:ServerSocket
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务端已开启,等待客户端的连接...");
//侦听客户端的连接
Socket socket = serverSocket.accept();
//阻塞式方法
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int read = inputStream.read(bytes);
String hostAddress = socket.getInetAddress().getHostAddress();
int port = socket.getPort();
String msg = new String(bytes, 0, read);
System.out.println("收到" + hostAddress + ":" + port + "发来的数据:" + msg);
//收到192.168.137.1:56934发来的数据:你好TCP,我来了
//服务端给客户端一个反馈
OutputStream outputStream = socket.getOutputStream();
outputStream.write("收到~".getBytes());
socket.close();
serverSocket.close();
}
}
服务端
package org.westos.demo5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author lwj
* @date 2020/6/13 14:52
*/
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(7777);
System.out.println("服务器端已开启,正在等待连接...");
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String msg = null;
while ((msg = reader.readLine()) != null) {
System.out.println(msg);
}
socket.close();
serverSocket.close();
}
}
客户端
package org.westos.demo5;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author lwj
* @date 2020/6/13 14:49
*/
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 7777);
OutputStream outputStream = socket.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("请输入待传递的信息:");
String msg = reader.readLine();
if ("886".equals(msg)) {
break;
}
writer.write(msg);
writer.newLine();
//一定要写入一个换行符,不然readLine()方法不起作用
writer.flush();
}
socket.close();
}
}
客户端上传
package org.westos.demo5;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author lwj
* @date 2020/6/13 14:59
*/
public class MyClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
OutputStream outputStream = socket.getOutputStream();
//获取一个输出流
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
//构造一个带缓冲区的字符输出流
BufferedReader reader = new BufferedReader(new FileReader(new File("src/org/westos/demo5/TCPClient.java")));
//待上传文件
String msg = null;
while ((msg = reader.readLine()) != null) {
writer.write(msg);
writer.newLine();
writer.flush();
}
socket.close();
}
}
服务器端保存
package org.westos.demo5;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author lwj
* @date 2020/6/13 14:59
*/
public class MyServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务器端已开启,正在等待连接...");
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("src/org/westos/demo5/TCPClient.txt")));
String msg = null;
while ((msg = reader.readLine()) != null) {
writer.write(msg);
writer.newLine();
writer.flush();
}
socket.close();
serverSocket.close();
}
}
TCPClient.txt
package org.westos.demo5;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author lwj
* @date 2020/6/13 14:49
*/
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 7777);
OutputStream outputStream = socket.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("请输入待传递的信息:");
String msg = reader.readLine();
if ("886".equals(msg)) {
break;
}
writer.write(msg);
writer.newLine();
writer.flush();
}
socket.close();
}
}
package org.westos.demo5;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author lwj
* @date 2020/6/13 14:59
*/
public class MyServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务器端已开启,正在等待连接...");
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("src/org/westos/demo5/upload.txt")));
String msg = null;
while ((msg = reader.readLine()) != null) {
/*if ("over".equals(msg)) {
break;
}*/
writer.write(msg);
writer.newLine();
writer.flush();
}
/*
如果上传成功,服务端给客户端一个反馈
(客户端在等待服务端给他反馈,服务端在等待客户端啥时候可以传递完文件)
客户端在读取文件时,可以以null为结尾结束while循环
但是在通道中读取数据时,不可以以null为条件来结束循环,导致readLine()方法会一直被阻塞,这就需要客户端在传递信息时传递一个标记
*/
OutputStream outputStream = socket.getOutputStream();
outputStream.write("上传完毕".getBytes());
socket.close();
serverSocket.close();
}
}
package org.westos.demo5;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* @author lwj
* @date 2020/6/13 14:59
*/
public class MyClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
OutputStream outputStream = socket.getOutputStream();
//获取一个输出流
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
//构造一个带缓冲区的字符输出流
BufferedReader reader = new BufferedReader(new FileReader(new File("src/org/westos/demo5/TCPClient.java")));
//待上传文件
String msg = null;
while ((msg = reader.readLine()) != null) {
writer.write(msg);
writer.newLine();
writer.flush();
}
/*
接收服务端的反馈
1、自定义结束标记
2、调用Socket的方法
*/
/*
writer.write("over");
writer.newLine();
writer.flush();*/
socket.shutdownOutput();
byte[] bytes = new byte[1024];
InputStream inputStream = socket.getInputStream();
int read = inputStream.read(bytes);
String s = new String(bytes, 0, read);
System.out.println(s);
//上传完毕
socket.close();
}
}
package org.westos.demo6;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author lwj
* @date 2020/6/13 16:01
*/
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5555);
System.out.println("服务器已经开启,正在等待连接...");
while (true) {
Socket socket = serverSocket.accept();
new UploadFileThread(socket).start();
}
}
}
package org.westos.demo6;
import java.io.*;
import java.net.Socket;
/**
* @author lwj
* @date 2020/6/13 16:03
*/
public class UploadFileThread extends Thread {
private Socket socket;
public UploadFileThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(System.currentTimeMillis() + "-upload.txt")));
String msg = null;
while ((msg = reader.readLine()) != null) {
writer.write(msg);
writer.newLine();
writer.flush();
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("上传完毕".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
每连接一个客户端,服务器端开启一个线程来处理,把socket传递给线程类。
package org.westos.demo;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
/**
* @author lwj
* @date 2020/6/13 16:16
*/
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("C:\\Users\\shawn\\Music\\戴爱玲 _ 刘伟德 - Gentleman.mp3")));
byte[] bytes = new byte[1024 * 8];
int len = 0;
OutputStream outputStream = socket.getOutputStream();
while ((len = bis.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
socket.shutdownOutput();
//接收服务端反馈
InputStream inputStream = socket.getInputStream();
int read = inputStream.read(bytes);
System.out.println(new String(bytes, 0, read));
}
}
package org.westos.demo;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author lwj
* @date 2020/6/13 16:19
*/
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已开启,正在等待连接...");
while (true) {
Socket socket = serverSocket.accept();
new Thread(new UploadThread(socket)).start();
}
}
}
package org.westos.demo;
import java.io.*;
import java.net.Socket;
/**
* @author lwj
* @date 2020/6/13 16:20
*/
public class UploadThread implements Runnable {
private Socket socket;
public UploadThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024 * 8];
int len = 0;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(System.currentTimeMillis() + "-upload.mp3")));
while ((len = inputStream.read(bytes)) != -1) {
bos.write(bytes, 0, len);
bos.flush();
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("上传完毕".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}
30、网络编程(InetAddress、UDP通信、TCP通信、上传文件并反馈、多线程实现上传音频文件)
标签:服务端 date com xxx rgs 条件 down writer imp
原文地址:https://www.cnblogs.com/shawnyue-08/p/13118164.html