我目前正在使用服务器/客户端编写套接字视频播放器程序。请注意,我是Java(eclipse)的新手
我设法让两者相互联系。首先,服务器发送它的视频名称列表,然后客户端点击(Jbox)并发回所选择的相应视频。然后,服务器将视频流式传输到客户端播放器。
我现在唯一的问题是在视频运行时等待不同的视频选择信号时,在主代码的后台运行方法(?)。如果不暂停主代码,我将如何做到这一点?我意识到主代码和等待信号代码必须同时运行。我正在寻找有人将我转到一个带示例的简单指南。
谢谢
答案 0 :(得分:0)
一种可能的方法是使用线程。服务器将使用一个线程(可能是主线程)来发送视频列表,当服务器收到请求时,它会启动一个线程,在单独的线程中将视频流发送到客户端。
答案 1 :(得分:0)
你可以这样做:
创建一个CallbackObject
,用于存储回调函数所需的内容,例如消息:
public class CallbackObject {
/* Any members you need for the callback object .. */
private String message;
public CallbackObject(String message) {
this.message = message;
}
/*
* Call this function when the thread has finished e.g.
* finished waiting, processing, etc. You could also just
* set a flag for the main thread here.
*/
public void callbackFunction() {
System.out.println("CALLBACK MESSAGE: \"" + this.message + "\"");
}
/*
* Allows you to modify your shared data. This is where you could
* also set e.g. a selected video, ready for the main thread to
* pick up. Note that 'synchronized' ensures that only one thread
* at a time can modify 'this.message'.
*/
public void clearMessage(String newMessage) {
synchronized(this.message) {
this.message = newMessage;
}
}
/*
* Get the shared data.
*/
public String getMessage() {
return this.message;
}
}
您可以将此回调对象传递给线程,例如WorkerThread
等待,处理或执行您想要的任何操作,但使用CallbackObject
来更改或处理数据:
public class WorkerThread extends Thread {
/* Our callback object */
private CallbackObject callbackObject;
public WorkerThread (CallbackObject callbackObject) {
this.callbackObject = callbackObject;
}
/*
* Main function of the thread.
*/
public void run() {
System.out.println("Hello from WorkerThread!");
try {
// THIS THREAD SLEEPS FOR ONE SECOND
Thread.sleep(1000);
// In YOUR program you wait for input or do whatever here
} catch (InterruptedException e) {
e.printStackTrace();
}
callbackObject.callbackFunction();
callbackObject.clearMessage("<empty message>");
System.out.println("CallbackThread done.");
}
}
您可以这样使用它:
public static void main(String[] args) {
CallbackObject callbackObject = new CallbackObject("Callback object message!");
WorkerThread workerThread = new WorkerThread(callbackObject);
workerThread.start();
String exitCmd = new String();
Scanner in = new Scanner(System.in);
// ENTER 'exit' TO STOP THE PROGRAM
while(exitCmd.equals("exit") == false) {
exitCmd = in.nextLine();
}
in.close();
System.out.println("CallbackObject (empty) message: " + callbackObject.getMessage());
System.out.println("Exiting ..");
}
正如您所看到的,您还可以看到在回调线程退出后主线程上对message
所做的更改。