服务端设置
//服务端
@Order(value = 10)
@Component
public class TpcServer implements ApplicationRunner{//服务启动是方法自动启动
private int port = 9989;// 默认服务器端口
private Logger log;
public TpcServer() {
}
// 创建指定端口的服务器
public TpcServer(int port) {//构造方法
this.port = port;//将方法参数赋值给类参数
}
// 提供服务
@Override
public void run(ApplicationArguments args) throws Exception {
Socket socket = null;
try {// 建立服务器连接
ServerSocket server = new ServerSocket(8880);//创建 ServerSocket类
//Socket socket = server.accept();// 等待客户连接
while(true){
try {
socket = server.accept();// 等待客户连接
} catch (Exception e) {
System.out.println("建立与客户端的连接出现异常");
e.printStackTrace();
}
ServerThread thread = new ServerThread(socket);
thread.start();
}
} finally {// 建立连接失败的话不会执行socket.close();长连接的话就不需要关闭
socket.close();//关闭连接
server.close();//关闭
}
} catch (IOException e) {//捕获异常
e.printStackTrace();
}
}
/*public static void main(String[] args) {//主程序方法
new TpcServer().service();//调用 service方法
}*/
}
public class ServerThread extends Thread {
private Socket socket ;
InputStream inputStream;
OutputStream outputStream;
public ServerThread(Socket socket){
this.socket=socket;
}
public void run(){
try {
while (true){
//接收客户端的消息并打印
System.out.println(socket);
inputStream=socket.getInputStream();
byte[] bytes = new byte[1024];
inputStream.read(bytes);
String string = new String(bytes);
System.out.println(string);
//向客户端发送消息
outputStream = socket.getOutputStream();
outputStream.write("OK".getBytes());
System.out.println("OK");
}
} catch (Exception e) {
System.out.println("客户端主动断开连接了");
//e.printStackTrace();
}
//操作结束,关闭socket
try{
socket.close();
}catch(IOException e){
System.out.println("关闭连接出现异常");
e.printStackTrace();
}
}
}
客户端
//客户端
public class TpcClient {
//private String host = "119.96.177.26";// 默认连接到本机
private String host = "10.7.229.101";// 默认连接到本机
private int port = 8880;// 默认连接到端口8189
public TpcClient() {
}
// 连接到指定的主机和端口
public TpcClient(String host, int port) {//构造方法
this.host = host;//将构造方法的参数host传递给类变量host
this.port = port;//将构造方法的参数port传递给类变量port
}
public void chat() {//chat方法
try {
// 连接到服务器
Socket socket = new Socket(host, port);//创建Socket类对象
try {
DataInputStream in = new DataInputStream(socket
.getInputStream());// 读取服务器端传过来信息的DataInputStream
DataOutputStream out = new DataOutputStream(socket
.getOutputStream());// 向服务器端发送信息的DataOutputStream
Scanner scanner = new Scanner(System.in);// 装饰标准输入流,用于从控制台输入
while (true) {
String send = scanner.nextLine();//读取控制台输入的内容
System.out.println(send);//输出键盘输出内容提示 ,也就是客户端向服务器端发送的消息
// 把从控制台得到的信息传送给服务器
out.writeUTF(send);//将客户端的信息传递给服务器
//String accpet = in.readUTF();// 读取来自服务器的信息
//System.out.println(accpet);//输出来自服务器的信息
}
} finally {
//socket.close();//关闭Socket监听
}
} catch (IOException e) {//捕获异常
e.printStackTrace();
}
}
public static void main(String[] args) {//主程序方法
new TpcClient().chat();//调用chat方法
}