EchoServer
package coozplz.example;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MultiThreadEchoServerMain extends Thread {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(9999);
System.out.println("서버 소켓 생성 완료");
while (true) {
Socket sock = ss.accept();
System.out.println(sock.getInetAddress().toString() + " // is connted");
MultiThreadEchoServer client = new MultiThreadEchoServer(sock);
client.start();
}
}
}
class MultiThreadEchoServer extends Thread {
Socket socket;
InputStream in;
OutputStream os;
public MultiThreadEchoServer(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
System.out.println("MultiThreadEchoServer is Running");
try {
in = socket.getInputStream();
os = socket.getOutputStream();
byte[] buf = new byte[1024];
int count;
while ((count = in.read(buf)) > 0) {
System.out.println("received: " + new String(buf, 0, count));
os.write(buf, 0, count);
System.out.println("write:" + new String(buf, 0, count));
}
os.close();
System.out.println("연결종료");
} catch (IOException ex) {
Logger.getLogger(MultiThreadEchoServerMain.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(MultiThreadEchoServerMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
Echo Client
package coozplz.example;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
public class EchoClientThread {
public static void main(String[] ar) throws IOException {
EchoClientThread client = new EchoClientThread();
client.process();
}
public void process() throws IOException {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("127.0.0.1", 9999));
OutputStream os = socket.getOutputStream();
InputStream in = socket.getInputStream();
byte[] buf = new byte[1024];
int count = 0;
while ((count = System.in.read(buf)) > 0) {
os.write(buf, 0, count);
System.out.println("Client -> Svr: " + new String(buf, 0, count));
count = in.read(buf);
System.out.println("Svr -> Client: " + new String(buf, 0, count));
}
os.close();
while ((count = in.read(buf)) > 0) {
System.out.write(buf, 0, count);
}
System.out.close();
System.out.println("연결종료");
if (socket != null) {
socket.close();
}
}
}