如服务端开启,立马连接并显示,未开启,一直等待。
准备用此方法,把以前写的终端运行的无图型界面的聊天程序改为图形界面。
无ui终端java增加图形界面,主要处理键盘输入和显示两部份。键盘输入采用键盘事件处理方式,显示采用动画原理,定时刷新完成。
ui界面的客户端:
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
public class App extends Application {
static String s=""; //通过静态s ui与Test3线程交换数据
public void start(Stage primaryStage) throws Exception {
Text text=new Text();
text.setX(50);
text.setY(60);
text.setFont(new Font(40));
Group group=new Group(text);
EventHandler<ActionEvent> eventHandler = e -> {
text.setText(s); //更新text内容
};
//------------这四句非常重要,它的作用是定时更新text内容---------------------------------------
KeyFrame keyFrame=new KeyFrame(Duration.millis(1),eventHandler); //每隔1ms相应一次eventHandler事件
Timeline timeline = new Timeline(keyFrame); //ui定时显示static s的内容。
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
//---------------------------------------------------------------------------------------
Scene scene = new Scene(group, 400, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) throws InterruptedException, IOException {
Thread t = new Test3();
t.start();
System.out.println(1);
launch(args); //启动ui 同时运行的还有serversocket线程
}
}
class Test3 extends Thread{
public void run() {
while (true) {
try {
Socket socket = new Socket("127.0.0.1", 3000);
while (true) {
InputStream inputStream = socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
App.s = objectInputStream.readUTF();
}
} catch (IOException e) {
App.s = "no link server";
// throw new RuntimeException(e);
}
}
}
}
无ui界面的服务端:
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Khd2{
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket serverSocket=new ServerSocket(3000);
Socket socket=serverSocket.accept();
int n=100;
while(true) {
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeUTF(String.valueOf(n));
objectOutputStream.flush();
System.out.println("ok");
Thread.sleep(1000);
n++;
}
}
}