一、什么是socket编程
socket编程,是在不同的进程间进行网络通讯的一种编程技术,在socket编程中基于TCP、UDP等协议做的一层封装,是一套系统所提供的的用于进行网络通信的编程接口。
二、 java实现socket代码
客户端java代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class TcpSocketClient {
/**
* 客户端程序
*/
public void client() throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("等待连接服务端!");
Socket socket = new Socket("127.0.0.1", 2111);
System.out.println("连接服务端成功!");
while (true) {
// 给服务端发信息
System.out.print("请输入:");
String s = scanner.next();
if ("out".equals(s)) {
break;
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write(s.getBytes(StandardCharsets.UTF_8));
byte[] bytes = new byte[1024];
// 读一下服务端发来的信息
InputStream inputStream = socket.getInputStream();
int read = inputStream.read(bytes);
System.out.println("服务端:" + new String(bytes, 0, read, Charset.defaultCharset()));
}
}
public static void main(String[] args) throws IOException {
TcpSocketClient tcpSocketServer = new TcpSocketClient();
tcpSocketServer.client();
}
}
服务端java代码:
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class TcpSocketServer {
/**
* 服务端程序
*/
public void server() throws IOException {
Scanner scanner = new Scanner(System.in);
// 服务端监听 1111 端口
ServerSocket serverSocket = new ServerSocket(1111);
System.out.println("等待连接");
Socket client = serverSocket.accept();
System.out.println("连接成功!");
while (true) {
// 获取客户端输入流
InputStream inputStream = client.getInputStream();
byte[] bytes = new byte[1024];
int read = inputStream.read(bytes);
// 客户端发来的消息
System.out.println("客户端:" + new String(bytes, 0, read, Charset.defaultCharset()));
// 给客户端发端消息
System.out.print("请输入:");
String nextLine = scanner.next();
if ("out".equals(nextLine)) {
break;
}
client.getOutputStream().write(nextLine.getBytes(StandardCharsets.UTF_8));
}
}
public static void main(String[] args) throws IOException {
TcpSocketServer tcpSocketServer = new TcpSocketServer();
tcpSocketServer.server();;
}
}
三、socket测试流程分析
先启动服务端server,再启动客户端client,等待提示连接成功后就可以测试发信息了
server启动连接:
client启动连接:
流程分析: