보라색이 main-T, 메인스레드가 할 일 보라색, 초록색이 파생된 새로운 스레드, 위에는 먼저 보내고 수신받는 순서로 갔는데
보내기와 받는 것 멀티스레드로, 순서대로 아님
package com.my.tcp.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
class ReceiveForClientMultiThread extends Thread{
private Socket s;
private InputStream is = null;
private DataInputStream dis =null;
public ReceiveForClientMultiThread(Socket s) throws IOException {
this.s = s;
is = s.getInputStream();
dis = new DataInputStream(is);
}
@Override
public void run() {
try {
String receiveMsg;
while( !(receiveMsg = dis.readUTF()).equals("quit") ) {
System.out.println("클라이언트가 보낸 메시지:" + receiveMsg);
}
} catch (IOException e) {
} finally {
System.out.println("클라이언트와의 연결이 종료되었습니다");
if(s != null) {
try {
s.close();
} catch (IOException e) {
}
}
}
}
}
class SendForClientMultiThread extends Thread{
private Socket s;
private OutputStream oos = null;
private DataOutputStream dos = null;
SendForClientMultiThread(Socket s) throws IOException {
this.s = s;
oos = s.getOutputStream();
dos = new DataOutputStream(oos);
}
@Override
public void run() {
try {
for(int i=0; i<100; i++) {
dos.writeUTF("fromServerMsg-" + i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ServerForClientMultiThread {
public static void main(String[] args) {
int port = 5432;
ServerSocket ss = null;
Socket s = null;
try {
ss = new ServerSocket(port);
while(true) {
try {
System.out.println("클라이언트 접속을 기다리기");
s = ss.accept();
//수신용스레드
new ReceiveForClientMultiThread(s).start();
//송신용스레드
new SendForClientMultiThread(s).start();
} catch(EOFException e) {
} catch (IOException e) {
e.printStackTrace();
}
}//end while
} catch(BindException e) {
System.out.println(port +"포트가 이미 사용중입니다");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
package com.my.tcp.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
class ClientThread extends Thread{
private Socket s;
private InputStream is = null;
private DataInputStream dis = null;
ClientThread(Socket s) throws IOException {
this.s = s;
is = s.getInputStream();
dis = new DataInputStream(is);
}
@Override
public void run() {
// while(true) {
// try {
// String receiveMsg;
// receiveMsg = dis.readUTF(); // while 반복문 안에서 catch 한번 들어가면 망가짐. 소켓 한번 망가지면 복구 안됨
// 그래서 아래처럼 try catch를 밖으로 꺼냄
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
try {
while(true) {
String receiveMsg;
receiveMsg = dis.readUTF();
System.out.println("서버가 되돌려준 메시지:" + receiveMsg);
}
} catch (SocketException e) {
} catch (EOFException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientMultiThread {
public static void main(String[] args) {
Socket s = null; // 네트워크는 무조건 혼자 test해봐야함
// String serverIP = "127.0.0.1"; // localhost, ip는 cmd창에서 확인
// String serverIP = "192.168.1.83"; // 옆자리 컴퓨터
String serverIP = "192.168.1.84"; // 교수님 컴퓨터
int serverPort = 5432;
OutputStream oos = null;
DataOutputStream dos = null;
Scanner sc = new Scanner(System.in);
try {
s = new Socket(serverIP, serverPort);
System.out.println("서버와 연결 성공");
new ClientThread(s).start(); // 새로운 스레드 시작
oos = s.getOutputStream();
dos = new DataOutputStream(oos);
String sendMsg;
do {
System.out.print("서버로 보낼 메시지 (종료하려면 quit을 입력하세요.):");
sendMsg = sc.nextLine();
dos.writeUTF(sendMsg);
} while (!sendMsg.equals("quit"));
} catch (EOFException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
System.out.println(serverIP + " 서버는 존재하지 않습니다. 서버IP를 확인하세요");
} catch (ConnectException e) {
System.out.println("서버가 실행되지 않았습니다. 서버실행을 확인하세요");
} catch (SocketException e) {
System.out.println("서버가 강제종료되었습니다. 서버확인하세요");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(s != null) {
try {
s.close();
} catch (IOException e) {
}
}
}
}
}
결과