我有一个相对简单的程序,我尝试建立客户端服务器连接,同时我在客户端使用线程来允许多个连接。
我运行服务器,然后服务器调用客户端构造函数并将端口连接传递给客户端,并在客户端启动线程。
我遇到的问题是,当我运行服务器端时,它不想超出构造函数调用范围。它似乎陷入了构造函数。
抱歉,这一切听起来有点令人困惑
也许有什么想法
这是服务器端
ServerMultipleThreads()
{
System.out.println("Starting the server first...");
try
{
ServerSoc = new ServerSocket(7777);
listening = true;
}
catch(Exception e)
{
System.out.println(e.toString());
System.exit(1);
}
System.out.println("The server has started running");
while(listening)
{
try
{
//creating the client socket and starting the new client session
new ClientSession(ServerSoc.accept());
System.out.println("The clientSession was called");
in = new DataInputStream(clientSocket.getInputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(in));
os = new PrintStream(clientSocket.getOutputStream());
while(true)
{
line = is.readLine();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myFile,txt")), true);
out.println(line);
}
}
catch(IOException ioe)
{
System.out.println(ioe.toString());
}
}
}
这是在客户端
ClientSession(Socket s)
{
clientSocket = s;
try
{
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out.println("Welcome");
}
catch(IOException exe)
{
System.out.println(exe.toString());
}
//starting the thread
while(runner == null)
{
runner = new Thread(this);
runner.start();
}
}
public void run()
{
while(runner == Thread.currentThread())
{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String stdIn;
try
{
while((stdIn = buf.readLine()) != null)
{
out.println(stdIn);
}
}
catch(IOException exe)
{
exe.toString();
}
try
{
Thread.sleep(10);
}
catch(InterruptedException e){}
}
亲切的问候 阿里安
最佳答案
这是因为 ServerSocket.accept()
会阻塞,直到收到客户端请求为止。
您需要有一个客户端调用服务器,如下所示:
Socket socket = new Socket(host, port);
InputStream in = socket.getInputStream();
// write some data...
关于java - 从服务器到客户端的套接字通信困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9391568/