고객이 서버에 붙으면 서버가 각 고객들에게 접속을 매번 맺고 끊으며 메세지를 전해주는 방식

고객은 익명 쓰레드가 계속 돌며 메세지를 수신

전송 IP와 수신 IP가 달라 지속적인 메세지 송수신 가능




package thread1;


import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Scanner;


public class MultiClient1 {

Scanner keyScanner;

public MultiClient1() {

keyScanner = new Scanner(System.in);

}

public void sendMsg()throws Exception{

while(true){

System.out.println("보낼 메시지 입력");

String msg = keyScanner.nextLine()+"\n";

Socket socket = new Socket("192.168.0.46", 5555);

OutputStream out = socket.getOutputStream();

out.write(msg.getBytes());

out.flush();

out.close();

socket.close();

}

}

public void receiveMsg()throws Exception{

final ServerSocket myServer = new ServerSocket(5554);

new Thread(){

@Override

public void run() {

while(true){

try{

Socket socket = myServer.accept();

Scanner scanner = new Scanner(socket.getInputStream());

System.out.println(scanner.nextLine());

scanner.close();

socket.close();

}catch(Exception e){

e.printStackTrace();

}

}

}

}.start();

}

public static void main(String[] args) throws Exception{

MultiClient1 cl = new MultiClient1();

cl.receiveMsg();

cl.sendMsg();

}

}




--------------------------------------------------------------------------------------------------



package thread1;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.HashMap;

import java.util.Map;

import java.util.Scanner;


public class MultiServer1 {

private ServerSocket serverSocket;

private Map<String, String> ipMap;

public MultiServer1()throws Exception{

ipMap = new HashMap<String, String>();

ipMap.put("ph", "192.168.0.46");

ipMap.put("yh", "192.168.0.46");

ipMap.put("yc", "192.168.0.46");

serverSocket = new ServerSocket(5555);

}

public void waitClient(){

while(true){

try{

System.out.println("대기중");

Socket socket = serverSocket.accept();

Scanner scanner = new Scanner(socket.getInputStream());

//ph|yh|밥먹었냐?\n

String userMsg = scanner.nextLine();

String[] msgArr = userMsg.split("\\|");

String targetIp = ipMap.get(msgArr[1]);

Socket clientSocket = new Socket(targetIp, 5554);

OutputStream clientOut = clientSocket.getOutputStream();

clientOut.write( (userMsg+"\n").getBytes());

clientOut.flush();

clientOut.close();

clientSocket.close();

scanner.close();

socket.close();

}catch(Exception e){

e.printStackTrace();

}finally{

}//end finally

}//end while

}//end waitClient

public static void main(String[] args)throws Exception {

MultiServer1 server = new MultiServer1();

server.waitClient();

}

}



Posted by 타다키치
,