socket的简单介绍与使用
1.介绍:
Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。
2.网络模型:
3.与http、webSocket 的区别:
a:socket:是位于应用层和传输控制层之间的一组接口。
b:http:属于应用层的单向通信协议。
c:webSocket:属于应用层的双向通信协议,即可以双向发送或接受信息。
4.基于tcp的Socket代码:
a:客户端
package com.liu.shiro;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;
public class TestSoketClient {
private static OutputStream outputStream;
private static BufferedWriter bufferedWriter;
private static Socket socket;
static void socketClient() throws IOException {
try {
socket = new Socket("127.0.0.1", 8888);
System.out.println("客户端成功!");
outputStream = socket.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
while (true) {
String data = new Scanner(System.in).nextLine();
bufferedWriter.write(data);
bufferedWriter.write("\n");
bufferedWriter.flush();
}
} finally {
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (socket != null) {
socket.close();
}
}
}
public static void main(String[] args) throws IOException {
socketClient();
}
}
b:服务端
package com.liu.shiro;
import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
class TestSoketServer {
private static ServerSocket serverSocket;
private static InputStream inputStream;
private static BufferedReader bufferedReader;
static void socketServer() throws IOException {
try {
serverSocket = new ServerSocket(8888);
System.out.println("服务器启动成功!");
while (true) {
Socket accept = serverSocket.accept();
inputStream = accept.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
if (line.equals("88")) {
System.out.println("关闭连接");
break;
}
}
bufferedReader.close();
inputStream.close();
accept.close();
}
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
if (inputStream != null) {
inputStream.close();
}
if (serverSocket != null) {
serverSocket.close();
}
}
}
public static void main(String[] args) throws IOException {
socketServer();
}
}
|