8. package com.example;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* This class launches the web application in an embedded Jetty container.
* This is the entry point to your application. The Java command that is used for
* launching should fire this main method.
*
*/
public class ChatServer {
public void start(int port) {
ServerSocket server;
Socket socket;
ChatServerThread thread;
try {
server = new ServerSocket(port);
System.err.println("ChatServer start" +
"?nIP
Address:"
InetAddress.getLocalHost().getHostAddress()
+ "?nPort:" + port);
while (true) {
try {
socket = server.accept();
thread = new ChatServerThread(socket);
thread.start();
} catch (IOException e) {
System.out.println(e);
}
+
9. }
} catch (IOException e) {
System.err.println(e);
}
}
public static void main(String[] args) throws Exception{
ChatServer server = new ChatServer();
server.start(8080);
}
}
○ChatServerThread.java
package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ChatServerThread extends Thread {
private
static
List<ChatServerThread>
ArrayList<ChatServerThread>();
private Socket socket;
public ChatServerThread(Socket socket) {
super();
this.socket = socket;
threads.add(this);
}
threads
=
new
10. public void run() {
InputStream in = null;
String message;
int size;
byte[] w = new byte[10240];
try {
System.err.println("ChatServerThread start");
in = socket.getInputStream();
while(true) {
try {
size = in.read(w);
if (size <= 0) {
throw new IOException();
}
message = new String(w, 0, size, "UTF8");
System.out.println(message);
sendMessageAll(message);
} catch(IOException e) {
System.out.println("ChatServerThread
stop");
socket.close();
threads.remove(this);
return;
}
}
} catch (IOException e) {
System.err.println(e);
}
}
public void sendMessageAll(String message) {
for (ChatServerThread thread : threads) {