0
我想做一个简单的客户端服务器网络程序。最初,我没有同时运行服务器和客户端对象。命令提示符只会试图运行该程序。然后我决定使用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();
}
}
任何提示和指针将不胜感激;我只需要点头(或更多)在正确的方向。