-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