자바 udp 2 인 다 중 스 레 드 채 팅

2391 단어
package study_04;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkServer implements Runnable{
	public static void main(String[] args) {
		new Thread(new TalkServer(9999)).start();//   
		new Thread(new TalkClient(1111, "localhost", 2222)).start();//   
	}
	private DatagramSocket server;
	
	public TalkServer(int port) {
		try {
			server = new DatagramSocket(port);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		while (true) {
		byte[] container = new byte[1024 *50];
		DatagramPacket packet = new DatagramPacket(container, 0,container.length);
		try {
			server.receive(packet);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		byte[] datas = packet.getData();
		String msg = new String(datas,0,datas.length);
		System.out.println(msg);
		if (msg.equals("bye")) {
			break;
		}
	}
	server.close();
	}

}	
package study_04;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;


public class TalkClient implements Runnable{
	public static void main(String[] args) {
		new Thread(new TalkClient(8888, "localhost", 9999)).start();
		new Thread(new TalkServer(2222)).start();

	}
	
	private DatagramSocket client;
	private BufferedReader reader;
	private String toIp;
	private int toPort;
	
	
	public TalkClient(int port,String toIp,int toPort) {
		this.toIp = toIp;
		this.toPort = toPort;
		try {
			client = new DatagramSocket(port);
			reader = new BufferedReader(new InputStreamReader(System.in));
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	@Override
	public void run() {
		while (true) {
			String data;
			try {
				data = reader.readLine();
				byte[] datas = data.getBytes();
				DatagramPacket packet = new DatagramPacket(datas, 0,data.length(),new InetSocketAddress(this.toIp,this.toPort));
				client.send(packet);
				if (data.equals("bye")) {
					break;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		client.close();
	}
	
}

좋은 웹페이지 즐겨찾기