シンプルなクライアント サーバー ネットワーク プログラムを作成しようとしています。最初は、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();
}
}
ヒントや指針をいただければ幸いです。正しい方向にうなずく必要があります。