-1
我正在使用A服务器,它可以接收来自所有客户端的消息并将它们发送给其他人。我可以收到消息,但我无法向所有客户端发送消息,尽管我从所有客户端获得正确的消息流。无法向所有客户端发送消息Java
这是我的代码 如果你想测试,请在cmd - >远程登录本地主机端口号
import java.io.*;
import java.util.*;
import java.net.*;
public class Server
{
private ServerSocket s;
private Hashtable saveOutputStreams = new Hashtable(500,80);
//Constructor
public Server(int port) throws IOException
{
listen(port);
}
//Listen method
public void listen(int port) throws IOException
{
s = new ServerSocket(port);
while(true)
{
Socket incoming = s.accept();
OutputStream sout = incoming.getOutputStream();
saveOutputStreams.put(incoming, sout);
Runnable r = new ThreadHandler(this,incoming);
Thread t = new Thread(r);
t.start();
}
}
// Create a table of streams to process in for loop of senToAll method
Enumeration getOutputStreams()
{
return saveOutputStreams.elements();
}
// Send message to all clients
public void sendToAll(String message)
{
synchronized(saveOutputStreams)
{
for(Enumeration e = getOutputStreams();e.hasMoreElements();)
{
OutputStream getOut = (OutputStream)e.nextElement();
PrintWriter outp = new PrintWriter(getOut);
try
{
outp.println("sent"+ message);
System.out.println("Stream: "+getOut);
System.out.println("PrinWriter "+outp);
}
catch(Exception ie)
{
ie.printStackTrace();
System.out.println("Error");
}
finally
{
System.out.println("done sen To All");
}
}
}
}
// Main
public static void main(String []args) throws IOException
{
new Server(8015);
}
}
class ThreadHandler implements Runnable
{
private Socket incoming;
private Server serverP;
public ThreadHandler(Server server, Socket socket)
{
serverP = server;
incoming = socket;
}
public synchronized void run()
{
try
{
try
{
InputStream inStream = incoming.getInputStream();
OutputStream outStream = incoming.getOutputStream();
Scanner in = new Scanner(inStream);
PrintWriter out = new PrintWriter(outStream,true);
out.println("TungAnh'Server");
String message = in.nextLine();
serverP.sendToAll(message);
out.println("receieve: "+message);
out.println("done");
System.out.println("current Stream: "+ outStream);
System.out.println("PrinWriter "+ out);
}
finally
{
incoming.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
究竟是什么呢?你究竟期待它做什么? – 2015-02-24 11:56:24
但这一行不起作用 outp.println(“sent”+ message); 我在printf流I从客户 流中获取:[email protected] PrinWriter [email protected]做仙至目前所有的流:[email protected] PrinWriter的Java。 [email protected] – 2015-02-24 12:08:46
两个流是相同的,但我不能写在它 – 2015-02-24 12:09:50