public void run() throws IOException {
server = new ServerSocket(port) {
protected void finalize() throws IOException {
this.close();
}
};
System.out.println("Server is running on port 12345");
while (true) {
// accepts a new client
Socket client = server.accept();
// get nickname of newUser
String nickname = (new Scanner ( client.getInputStream() )).nextLine();
nickname = nickname.replace(",", ""); // ',' use for serialisation
nickname = nickname.replace(" ", "_");
System.out.println("New Client: \"" + nickname + "\"\n\t Host:" + client.getInetAddress().getHostAddress());
// create new User
User newUser = new User(client, nickname);
// add newUser message to list
this.clients.add(newUser);
// Welcome msg
newUser.getOutStream().println(
"<img src='http://localhost:8000/welcome.gif' height='42' width='42'>"
+ "<b>Welcome</b> " + newUser.toString() +
"<img src='https://www.kizoa.fr/img/e8nZC.gif' height='42' width='42'>"
);
// create a new thread for newUser incoming messages handling
new Thread(new UserHandler(this, newUser)).start();
}
}
我有一个发送静态文件的http服务器。因此,如果我在浏览器中键入localhost:8000/welcome.gif
,则HTTP服务器会将图像发送到浏览器。但我希望Java客户端接收此图像。
这里是从客户端读取任何新消息的类
class Read extends Thread {
public void run() {
String message;
// till the this thread is interupted, it reads an input
// from the server
while(!Thread.currentThread().isInterrupted()){
try {
message = input.readLine();
System.out.println("Message sent from server is: "+message);
if(message != null){
// if the client accepts broadcast user message from
// the server, it must update their lists.
if (message.charAt(0) == '[') {
message = message.substring(1, message.length()-1);
ArrayList<String> ListUser = new ArrayList<String>(
Arrays.asList(message.split(", "))
);
jTextPane2.setText(null);
for (String user : ListUser) {
appendToPane(jTextPane2, "@" + user);
}
} else{
appendToPane(jTextPane1, message);
}
}
}
catch (IOException ex) {
System.err.println("Failed to parse incoming message");
}
}
}
}
服务器发送时,
"<img src='http://localhost:8000/welcome.gif' height='42' width='42'>"
+ "<b>Welcome</b> " + newUser.toString() +
"<img src='https://www.kizoa.fr/img/e8nZC.gif' height='42' width='42'>"
到客户端,它打印无法解析传入的消息。但是显示第二个带有src的图像https://www.kizoa.fr/img/e8nZC.gif。
任何帮助,不胜感激。