基于TCP/IP协议的通信
- TCP/IP协议
-
- TCP/IP协议.会在通信两端建立连接(虚拟连接),用于发送和接收数据
-
- TCP/IP协议是一种可靠的网络协议,它通过重发机制来保证这种可靠性
- 通信的实现
-
- ServerSocket用来监听来自客户端的连接,当没有连接时,它处于阻塞状态
-
- 客户端使用Socket连接到指定的服务器
基于UDP协议的通信
- UDP协议
-
- UDP协议不会在通信两端建立连接(虚拟链路),而是直接发送连接
-
- UDP协议是一种不可靠的网络协议,但是这种协议的通信效率非常高
- 通信的实现
-
- DatagramSocket用于两端的通信,它不负责 维护状态,不产生io流,仅仅是发送或接受数据包
-
- DatagramPacket代表数据包
InetAddress
public class InetAddressDemo {
public static void main(String[] args) throws IOException {
InetAddress baidu = InetAddress.getByName("www.baidu.com");
System.out.println(baidu);
System.out.println(baidu.getHostAddress());
System.out.println(baidu.isReachable(1000));
System.out.println("====================================================================================");
InetAddress local = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
System.out.println(local.getHostName());
System.out.println(local.isReachable(1000));
}
}
案例演示 (简易聊天室)
package javaserver.TcpServer;
import JAVAClient.TcpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class tcpServer {
public static ExecutorService threadPool= Executors.newFixedThreadPool(10);
public static List<Socket> socketList= Collections.synchronizedList(new ArrayList<>());
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(9000);
while (true){
Socket socket = serverSocket.accept();
socketList.add(socket);
threadPool.submit(new ThreadTask(socket));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ThreadTask implements Runnable{
private Socket socket;
private BufferedReader reader;
public ThreadTask(Socket socket) {
this.socket = socket;
try {
this.reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
String line;
while ((line=reader.readLine())!=null){
for (Socket client: tcpServer.socketList){
String from=socket.getInetAddress().getHostAddress()+":::"+socket.getPort();
String content= from+"说"+line;
new PrintStream(client.getOutputStream()).println(content);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package JAVAClient;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TcpClient {
public static ExecutorService threadPool= Executors.newFixedThreadPool(3);
public static void main(String[] args) throws IOException {
Socket socket=new Socket("127.0.0.1",9000);
threadPool.submit(new ReadTask(socket));
threadPool.submit(new WriteTask(socket));
}
}
class ReadTask implements Runnable{
private Socket socket;
private BufferedReader reader;
public ReadTask(Socket socket) {
this.socket = socket;
try {
this.reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
String line;
while ((line=reader.readLine())!=null){
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class WriteTask implements Runnable{
private Socket socket;
private PrintStream writer;
public WriteTask(Socket socket) {
this.socket = socket;
try {
writer=new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
String line;
while ((line=scanner.nextLine())!=null){
writer.println(line);
}
}
}
UDP 演示
服务端
package javaserver.TcpServer;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class UdpServer {
public static ExecutorService threadPool= Executors.newFixedThreadPool(10);
public static List<InetSocketAddress> addressesList=new ArrayList<>();
public static void main(String[] args) {
try {
DatagramSocket socket=new DatagramSocket(9001);
threadPool.submit(new SendTask(socket));
byte[] buffer=new byte[1024];
DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
while (true){
socket.receive(packet);
addressesList.add((InetSocketAddress) packet.getSocketAddress());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class SendTask implements Runnable{
private DatagramSocket socket;
public SendTask(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
Scanner scanner = new Scanner(System.in);
String line;
while ((line= scanner.nextLine())!=null){
for (InetSocketAddress isa:UdpServer.addressesList){
byte[] buffer=line.getBytes();
DatagramPacket packet=new DatagramPacket(buffer,buffer.length,isa.getAddress(),isa.getPort());
socket.send(packet);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端
package JAVAClient;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class UdpClient {
public static ExecutorService threadPool= Executors.newFixedThreadPool(3);
public static void main(String[] args) {
try {
DatagramSocket socket=new DatagramSocket();
DatagramPacket packet=new DatagramPacket(new byte[]{1},1, InetAddress.getByName("127.0.0.1"),9001);
socket.send(packet);
threadPool.submit(new ReceiveTask(socket));
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ReceiveTask implements Runnable{
private DatagramSocket socket;
public ReceiveTask(DatagramSocket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
byte[] buffer=new byte[1024];
DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
while (true){
socket.receive(packet);
String line =new String(packet.getData(),0, packet.getLength());
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|