socket简介
TCP和UDP直观区别
UDP实现回显服务
服务器端
代码简易实现
package network;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
public class UdpEchoServer {
private DatagramSocket socket=null;
public UdpEchoServer(int port) throws SocketException {
socket=new DatagramSocket(port);
}
public void start() throws IOException {
System.out.println("启动服务器!");
while(true){
DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
socket.receive(requestPacket);
String request=new String(requestPacket.getData(),0,requestPacket.getLength());
String response=process(request);
DatagramPacket responsePacket= new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
socket.send(responsePacket);
System.out.printf("[ %s : %d ] req: %s,resp: %s\n",
requestPacket.getAddress().toString(),requestPacket.getPort(),request,response);
}
}
public String process(String request){
return request;
}
public static void main(String[] args) throws IOException {
UdpEchoServer server=new UdpEchoServer(9090);
server.start();
}
}
代码说明
客户端
代码实现
package network;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
public class UdpEchoClient {
private DatagramSocket socket=null;
private String serverIP;
private int serverPort;
public UdpEchoClient(String ip,int port)throws SocketException{
socket=new DatagramSocket();
serverIP=ip;
serverPort=port;
}
public void start() throws IOException {
Scanner scanner=new Scanner(System.in);
while(true){
System.out.println("-> ");
String request=scanner.next();
DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
InetAddress.getByName(serverIP),serverPort);
socket.send(requestPacket);
DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
socket.receive(responsePacket);
String response=new String(responsePacket.getData(),0,responsePacket.getLength(),"UTF-8");
System.out.printf("req: %s,resq: %s \n",request,response);
}
}
public static void main(String[] args) throws IOException {
UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
client.start();
}
}
代码说明
重写process实现翻译查询
package network;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
public class UdpDictServer extends UdpEchoServer{
private HashMap<String, String> dict = new HashMap<>();
public UdpDictServer(int port) throws SocketException {
super(port);
dict.put( "cat","小猫");
dict.put("dog","小狗");
dict.put("fuck","卧槽");
dict.put("pig","小猪");
}
@Override
public String process(String request) {
return dict.getOrDefault(request, "该词无法被翻译!");
}
public static void main(String[] args) throws IOException {
UdpDictServer server = new UdpDictServer( 9090);
server.start();
}
}
注意!
TCP
服务器端代码
package TCPnetwork;
import UDPnetwork.UdpDictServer;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class TcpEchoServer {
private ServerSocket serverSocket=null;
public TcpEchoServer(int port) throws IOException {
serverSocket=new ServerSocket(port);
}
public void start() throws IOException {
System.out.println("服务器启动");
while(true){
Socket clientSocket=serverSocket.accept();
ProcessConnection(clientSocket);
}
}
private void ProcessConnection(Socket clientSocket) {
System.out.printf("[%s:%d] 客户端连接建立!",clientSocket.getInetAddress().toString(),clientSocket.getPort());
try(InputStream inputStream=clientSocket.getInputStream()){
try(OutputStream outputStream=clientSocket.getOutputStream()){
Scanner scanner=new Scanner(inputStream);
while(true){
if(!scanner.hasNext()){
System.out.printf("[%s:%d] 客户端断开连接!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
break;
}
String request=scanner.next();
String response=process(request);
PrintWriter printWriter=new PrintWriter(outputStream);
printWriter.println(response);
printWriter.flush();
System.out.printf("[%s:%d] req:%s,resp:%s\n",clientSocket.getInetAddress().toString(),
clientSocket.getPort(),request,response);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String process(String request) {
return request;
}
public static void main(String[] args) throws IOException {
TcpEchoServer server=new TcpEchoServer(9090);
server.start();
}
}
处理多个连接
多线程处理
代码实现
package TCPnetwork;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class TcpThreadEchoServer {
private ServerSocket serverSocket=null;
public TcpThreadEchoServer(int port) throws IOException {
serverSocket=new ServerSocket(port);
}
public void start() throws IOException {
System.out.println("服务器启动");
while(true){
Socket clientSocket=serverSocket.accept();
Thread t=new Thread(()->{
ProcessConnection(clientSocket);
});
t.start();
}
}
private void ProcessConnection(Socket clientSocket) {
System.out.printf("[%s:%d] 客户端连接建立!",clientSocket.getInetAddress().toString(),clientSocket.getPort());
try(InputStream inputStream=clientSocket.getInputStream()){
try(OutputStream outputStream=clientSocket.getOutputStream()){
Scanner scanner=new Scanner(inputStream);
while(true){
if(!scanner.hasNext()){
System.out.printf("[%s:%d] 客户端断开连接!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
break;
}
String request=scanner.next();
String response=process(request);
PrintWriter printWriter=new PrintWriter(outputStream);
printWriter.println(response);
printWriter.flush();
System.out.printf("[%s:%d] req:%s,resp:%s\n",clientSocket.getInetAddress().toString(),
clientSocket.getPort(),request,response);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String process(String request) {
return request;
}
public static void main(String[] args) throws IOException {
TcpThreadEchoServer server=new TcpThreadEchoServer(9090);
server.start();
}
}
线程池的代码实现
package TCPnetwork;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TcpThreadPollEchoServer {
private ServerSocket serverSocket=null;
public TcpThreadPollEchoServer(int port) throws IOException {
serverSocket=new ServerSocket(port);
}
public void start() throws IOException {
System.out.println("服务器启动");
ExecutorService pool= Executors.newCachedThreadPool();
while(true){
Socket clientSocket=serverSocket.accept();
pool.submit(new Runnable() {
@Override
public void run() {
ProcessConnection(clientSocket);
}
});
}
}
private void ProcessConnection(Socket clientSocket) {
System.out.printf("[%s:%d] 客户端连接建立!",clientSocket.getInetAddress().toString(),clientSocket.getPort());
try(InputStream inputStream=clientSocket.getInputStream()){
try(OutputStream outputStream=clientSocket.getOutputStream()){
Scanner scanner=new Scanner(inputStream);
while(true){
if(!scanner.hasNext()){
System.out.printf("[%s:%d] 客户端断开连接!\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
break;
}
String request=scanner.next();
String response=process(request);
PrintWriter printWriter=new PrintWriter(outputStream);
printWriter.println(response);
printWriter.flush();
System.out.printf("[%s:%d] req:%s,resp:%s\n",clientSocket.getInetAddress().toString(),
clientSocket.getPort(),request,response);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String process(String request) {
return request;
}
public static void main(String[] args) throws IOException {
TcpThreadPollEchoServer server=new TcpThreadPollEchoServer(9090);
server.start();
}
}
重写翻译查询语句代码实现
package TCPnetwork;
import UDPnetwork.UdpDictServer;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
public class TcpDictServer extends TcpEchoServer{
private HashMap<String, String> dict = new HashMap<>();
public TcpDictServer(int port) throws IOException {
super(port);
dict.put( "cat","小猫");
dict.put("dog","小狗");
dict.put("fuck","卧槽");
dict.put("pig","小猪");
}
@Override
public String process(String request) {
return dict.getOrDefault(request, "该词无法被翻译!");
}
public static void main(String[] args) throws IOException {
TcpDictServer server = new TcpDictServer( 9090);
server.start();
}
}
客户端代码
package TCPnetwork;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.security.spec.PSSParameterSpec;
import java.util.Scanner;
public class TcpEchoClient {
private Socket socket=null;
public TcpEchoClient(String serverIP,int serverPort) throws IOException {
socket=new Socket(serverIP,serverPort);
}
public void start(){
System.out.println("服务器连接成功!\n");
Scanner scanner=new Scanner(System.in);
try(InputStream inputStream=socket.getInputStream()) {
try (OutputStream outputStream = socket.getOutputStream()) {
while(true){
System.out.println("-> ");
String request=scanner.next();
PrintWriter printWriter=new PrintWriter(outputStream);
printWriter.println(request);
printWriter.flush();
Scanner respScanner=new Scanner(inputStream);
String response=respScanner.next();
System.out.printf("req: %s , resp: %s \n",request,response);
}
}
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
TcpEchoClient tcpEchoClient=new TcpEchoClient("127.0.0.1",9090);
tcpEchoClient.start();
}
}
|