[英]Simple Networking; Threads issue
我正在嘗試制作一個簡單的客戶端-服務器網絡程序。 最初,我沒有同時運行Server和Client對象。 命令提示符只會停留在嘗試運行程序上。 然后,我決定使用threads
。 結果是一樣的; 我相信我必須在某個地方使用wait()
和notify()
,但是我無法獲得它。 服務器需要首先運行,但是它必須等待incoming Socket
引用才能繼續。 我認為在實施wait-and-notify
機制之前,需要在某些地方四處移動。 到目前為止,這是我的代碼-:
package networking;
import java.net.*;
import java.io.*;
import java.util.Scanner;
class Server implements Runnable
{
ServerSocket ss;
Socket incoming;
public void run()
{
try
{
ss = new ServerSocket(8189);
incoming = ss.accept();
OutputStream outs = incoming.getOutputStream();
InputStream ins = incoming.getInputStream();
Scanner in = new Scanner(ins);
PrintWriter out = new PrintWriter(outs);
out.println("Hello, Bye to exit");
out.println("This is the server program");
out.println("It will echo client stuff");
boolean done = false;
while(!done && in.hasNextLine())
{
out.println("Echo: " + in.nextLine());
if(in.nextLine().trim().equals("Bye"))
done = true;
}
incoming.close();
}
catch(IOException e)
{
System.err.println(e.getMessage());
}
}
}
class Client implements Runnable
{
Socket s;
public void run()
{
try
{
s = new Socket("localhost", 8189);
InputStream ins = s.getInputStream();
OutputStream outs = s.getOutputStream();
Scanner in = new Scanner(ins);
PrintWriter out = new PrintWriter(outs);
while(in.hasNextLine())
System.out.println("Client: " + in.nextLine());
out.println("Bye");
s.close();
}
catch(IOException e)
{
System.err.println(e.getMessage());
}
}
}
public class Networking
{
public static void main(String... args)
{
Thread server = new Thread(new Server());
Thread client = new Thread(new Client());
server.start();
client.start();
}
}
任何提示和指示將不勝感激; 我只需要向正確的方向點頭(或更多)即可。
您打開服務和客戶的代碼正確。 但是問題在於在讀取或寫入數據的while循環中陷入了死鎖。 因為建立連接后,展位服務器和客戶端正在互相等待在流中寫入內容。 試試這個。
class Server implements Runnable {
ServerSocket ss;
Socket incoming;
public void run() {
try {
System.out.println("Server STarted");
ss = new ServerSocket(8189);
incoming = ss.accept();
System.out.println("Client accepted");
OutputStream outs = incoming.getOutputStream();
InputStream ins = incoming.getInputStream();
Scanner in = new Scanner(ins);
PrintWriter out = new PrintWriter(outs);
out.println("Hello, Bye to exit");
out.println("This is the server program");
out.println("It will echo client stuff");
boolean done = false;
while (!done) { // && in.hasNextLine()
// out.println("Echo: " + in.nextLine());
// if (in.nextLine().trim().equals("Bye")) {
// done = true;
// }
out.println("TEsting from server");
}
incoming.close();
System.out.println("End server");
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.