package com.socket;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;

public class MultiClient implements ActionListener {
	// Socket 통신을 위한 객체 선언
	private Socket socket;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;

	// 화면 UI를 위한 객체 선언
	private JFrame jframe;
	private JTextField jtf;
	private JTextArea jta;
	private JLabel jlb1, jlb2;
	private JPanel jp1, jp2;
	private JButton jbtn;

	// ip주소와 id저장
	private String ip;
	private String id;

	public MultiClient(String argIp, String argId) {
		ip = argIp;
		id = argId;
		jframe = new JFrame("Multi Chatting");
		jtf = new JTextField(30);
		jta = new JTextArea("", 10, 50);
		jlb1 = new JLabel("Usage ID : [[ " + id + "]]");
		jlb2 = new JLabel("IP : " + ip);
		jbtn = new JButton("종료");
		jp1 = new JPanel();
		jp2 = new JPanel();

		jlb1.setBackground(Color.yellow);
		jlb2.setBackground(Color.green);
		jta.setBackground(Color.pink);

		jp1.setLayout(new BorderLayout());
		jp2.setLayout(new BorderLayout());

		jp1.add(jbtn, BorderLayout.EAST);
		jp1.add(jtf, BorderLayout.CENTER);
		jp2.add(jlb1, BorderLayout.CENTER);
		jp2.add(jlb2, BorderLayout.EAST);

		jframe.add(jp1, BorderLayout.SOUTH);
		jframe.add(jp2, BorderLayout.NORTH);

		JScrollPane jsp = new JScrollPane(jta,
				JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
				JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		jframe.add(jsp, BorderLayout.CENTER);

		jtf.addActionListener(this);
		jbtn.addActionListener(this);
		jframe.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				try {
					oos.writeObject(id + "#exit");
				} catch (IOException ee) {
					ee.printStackTrace();
				}
				System.exit(0);
			}

			public void windowOpened(WindowEvent e) {
				jtf.requestFocus();
			}
		});
		jta.setEditable(false);
		Toolkit tk = Toolkit.getDefaultToolkit();
		Dimension d = tk.getScreenSize();
		int screenHeight = d.height;
		int screenWidth = d.width;
		jframe.pack();
		jframe.setLocation((screenWidth - jframe.getWidth()) / 2,
				(screenHeight - jframe.getHeight()) / 2);
		jframe.setResizable(false);
		jframe.setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		Object obj = e.getSource();
		String msg = jtf.getText();
		if (obj == jtf) {
			if (msg == null || msg.length() == 0) {
				JOptionPane.showMessageDialog(jframe, "글을 쓰세요", "경고",
						JOptionPane.WARNING_MESSAGE);
			} else {
				try {
					oos.writeObject(id + "#" + msg);
				} catch (IOException ee) {
					ee.printStackTrace();
				}
				jtf.setText("");
			}
		} else if (obj == jbtn) {
			try {
				oos.writeObject(id + "#exit");
			} catch (IOException ee) {
				ee.printStackTrace();
			}
			System.exit(0);
		}
	}

	public void exit(){
		System.exit(0);
	}

	public void init() throws IOException{
		socket = new Socket(ip,5000);
		System.out.println("connected....");
		oos = new ObjectOutputStream(socket.getOutputStream());
		ois = new ObjectInputStream(socket.getInputStream());
		
		MultiClientThread ct = new MultiClientThread(this);
		Thread t = new Thread(ct);
		t.start();
	}
	public static void main(String[] args) throws IOException {
		JFrame.setDefaultLookAndFeelDecorated(true);
		MultiClient cc = new MultiClient("211.183.2.80", "쌍칼");
		
		cc.init();
	}
	
	public ObjectInputStream getOis(){
		return ois;
	}
	public JTextArea getJta(){
		return jta;
	}
	public String getId(){
		return id;
	}
}




package com.socket;

public class MultiClientThread extends Thread {
	private MultiClient mc;

	public MultiClientThread(MultiClient mc) {
		this.mc = mc;
	}
	public void run() {
		String message = null;
		String[] receivedMsg = null;
		boolean isStop = false;
		while (!isStop) {
			try {
				message = (String) mc.getOis().readObject();
				receivedMsg = message.split("#");
			} catch (Exception e) {
				e.printStackTrace();
				isStop = true;
			}
			System.out.println(receivedMsg[0] + "," + receivedMsg[1]);
			if (receivedMsg[1].equals("exit")) {
				if (receivedMsg[0].equals(mc.getId())) {
					mc.exit();
				} else {
					mc.getJta().append(receivedMsg[0] 
							+"님이 종료 하셨습니다."+System.getProperty("line.separator"));
					mc.getJta().setCaretPosition(mc.getJta().getDocument().getLength());
				}
			}else{
				mc.getJta().append(receivedMsg[0]+" : "
						+receivedMsg[1]+System.getProperty("line.separator"));
				mc.getJta().setCaretPosition(mc.getJta().getDocument().getLength());
			}
		}
	}
}


'Java > 네트워크' 카테고리의 다른 글

채팅방 1  (0) 2012.04.13
네트워크  (0) 2012.04.13
package com.socket;//채팅방 클라이언트

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;


public class EchoClient {
	private String ip;
	private int port;
	private String str;
	BufferedReader file;
	public EchoClient(String ip, int port)throws IOException{
		this.ip =ip;
		this.port = port;
		Socket tcpSocket = getSocket();
		OutputStream os_socket = tcpSocket.getOutputStream();
		InputStream is_socket = tcpSocket.getInputStream();
		
		//서버로 전송할 데이터를 처리하기 위한 객체
		BufferedWriter bufferW = new BufferedWriter(new OutputStreamWriter(os_socket));
		//서버에서 전송된 데이터 를 처리하기 위한 객체
		BufferedReader bufferR = new BufferedReader(new InputStreamReader(is_socket));
		
		System.out.print("입력 : ");
		file = new BufferedReader(new InputStreamReader(System.in));
		str = file.readLine();
		str += System.getProperty("line.separator");
		
		//서버로 데이터 전송 작업 수행
		bufferW.write(str);
		bufferW.flush();
		
		//서버로 부터 전송된 데이터를 읽는 작업 수행
		str = bufferR.readLine();
		System.out.println("Echo Result : "+str);
		
		file.close();
		
		bufferW.close();
		bufferR.close();
		tcpSocket.close();
	}
	public Socket getSocket(){
		Socket tcpSocket = null;
		try{
			tcpSocket = new Socket(ip,port); 
		}catch (IOException ioe){
			ioe.printStackTrace();
			System.exit(0);
		}
		return tcpSocket;
	}
	public static void main(String[] args) throws IOException{
		new EchoClient("211.183.2.73",3000);
	}
}




package com.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class  EchoServer{
    private BufferedReader bufferR; 
    private BufferedWriter bufferW;
    private InputStream is;
    private OutputStream os;
    private ServerSocket serverS;
    public EchoServer(int port){
        try{
            serverS = new ServerSocket(port);
        }catch(IOException ioe){
            ioe.printStackTrace();
            System.exit(0);
        }
        while(true){
            try{
                System.out.println("클라이언트를 요청을 기다리는 중");
                Socket tcpSocket = serverS.accept();
                System.out.println("클라이언트의 IP 주소 : "+
                    tcpSocket.getInetAddress().getHostAddress());
                is = tcpSocket.getInputStream();
                os = tcpSocket.getOutputStream();
                bufferR = new BufferedReader(
                        new InputStreamReader(is));
                bufferW = new BufferedWriter(
                        new OutputStreamWriter(os));                
                String message = bufferR.readLine();
                System.out.println("수신메시지 : "+ message);
                message = message + 
                    System.getProperty("line.separator");
                bufferW.write(message);
                bufferW.flush();
                bufferR.close();
                bufferW.close();
                tcpSocket.close();
            }catch(IOException ioe){
                ioe.printStackTrace();
            }
        }    
    }
    public static void main(String[] args){
        new EchoServer(3000);
    }
}


'Java > 네트워크' 카테고리의 다른 글

채팅방2  (0) 2012.04.13
네트워크  (0) 2012.04.13
package com.basic;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class InetAddressTest02 {
	public static void main(String [] args) throws Exception{
		BufferedReader reader;
		String url = null;
		InetAddress addr = null;
		
		reader = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("웹사이트 주소를 입력하세요 ->");
		
		url = reader.readLine();
		
		try{
			addr = InetAddress.getByName(url);
		}catch(UnknownHostException e){
			e.printStackTrace();
		}
		System.out.println("==========================");
		//getHostAddress();
		System.out.println(url+"의 IP 번호 = "+addr.getHostAddress());
	}
}



package com.basic;

import java.net.URL;
import java.io.IOException;
import java.net.MalformedURLException;

public class URLEx {
	public static void main(String[] args) throws MalformedURLException, IOException{
		URL url = new URL("http://java.sun.com/index.jsp?name=syh1011#content");
		
		System.out.println("프로토콜 : "+url.getProtocol());
		System.out.println("호스트 : "+url.getHost());
		System.out.println("포트 : "+url.getDefaultPort());
		System.out.println("패스 : "+url.getPath());
		System.out.println("Query: "+url.getQuery());
		System.out.println("reference: "+url.getRef());
		System.out.println("주소: "+url.toExternalForm());
		
	}
}



package com.basic;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class NetworkEx4 {
	public static void main(String[] args) {
		URL url = null;
		BufferedReader input = null;
		String address = "http://www.google.co.kr";
		String line = "";

		try{
			//URL : 인터넷 URL 주소를 추상화 하는 클래스 
			url = new URL(address);

			//url.openStream() : URL객체에 저장된 URL주소의 데이터를 InputStream으로 반환
			input = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));

			while((line = input.readLine()) !=null) {
				System.out.println(line);
			}
			input.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}


'Java > 네트워크' 카테고리의 다른 글

채팅방2  (0) 2012.04.13
채팅방 1  (0) 2012.04.13

+ Recent posts