[App 개발] java2 network (chat server/client)
본문
//EchoClientTest.java
import java.io.*;
import java.net.*;
public class EchoClientTest{
public static void main(String[] args){
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
/* if (args.length<=1){
System.out.println("Usage : java EchoClientTest IPAdress port");
return;
} */
try{
echoSocket = new Socket(args[0], Integer.parseInt(args[1]));
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
}catch(UnknownHostException e){
System.err.println("unknown host can't find (_)");
System.exit(1);
}catch(IOException e){
System.err.println("I/O error ^_^");
System.exit(1);
}
try{
BufferedReader std_in;
String userInput;
std_in = new BufferedReader(new InputStreamReader(System.in));
while((userInput = std_in.readLine())!= null){
out.println(userInput);
System.out.println("ehco:"+in.readLine());
}
out.close();
in.close();
std_in.close();
echoSocket.close();
}catch (Exception e){
System.out.println("disconnected!");
}
}
}
//EchoServerTest.java
import java.net.*;
import java.io.*;
public class EchoServerTest{
public static void main(String[] args) {
ServerSocket serverSocket = null;
int port = 4444;
try{
serverSocket = new ServerSocket(port);
}catch(IOException e){
System.exit(1);
}
System.out.println("Server " + serverSocket.getInetAddress()
+" wait for connection at port"+ port);
Socket clientSocket = null;
try{
clientSocket = serverSocket.accept();
}catch(IOException e){
System.err.println("Failed Hi Hi Hi!");
System.exit(1);
}
try{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
System.out.println("Connected");
while((inputLine = in.readLine()) != null){
out.println(inputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}catch(IOException e){
System.out.println("Disconnected");
}
}
}
- 다중 클라이언트를 처리할수 있는 에코서버의 스레드 구현 버젼
//EchoServer_Thread.java
import java.net.*;
import java.io.*;
public class EchoServer_Thread{
public static void main(String[] args){
ServerSocket serverSocket = null;
int port = 4444;
boolean listening = true;
try{
serverSocket = new ServerSocket(port);
}catch(IOException e){
System.err.println("connection failed");
System.exit(-1);
}
System.out.println("Server n" + serverSocket + "n wait for connecting");
try{
while(listening){
new ServiceThread(serverSocket.accept()).start();
}
serverSocket.close();
}catch(IOException e){
System.out.println("Server ShutDown");
}
}
}
//ServiceThread.java
import java.io.*;
import java.net.*;
public class ServiceThread extends Thread{
private Socket cSocket = null;
public ServiceThread(Socket socket){
super("Echo Service Thread");
cSocket = socket;
}
public void run(){
try{
System.out.println("Client Infon" + cSocket + "was connected");
PrintWriter out = new PrintWriter(cSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader
(cSocket.getInputStream()));
String inputLine, outputLine;
while((inputLine = in.readLine()) != null){
out.println(inputLine);
}
out.close();
in.close();
cSocket.close();
}catch(IOException e){
System.out.println("Client Infon" + cSocket + "was disconnected");
}
}
}
-- UDP 기반 에코서버/클라이언트
//EchoClient_Datagram.java
import java.net.*;
import java.io.*;
public class EchoClient_Datagram{
public static void main(String[] args){
DatagramSocket dSocket;
DatagramPacket dPacket, send_dPacket;
InetAddress host;
int port;
byte[] buf = new byte[256];
if(args.length < 2){
System.out.println("사용법n"+
"java EchoServer_Datagram 서버이름 포트번호");
System.exit(1);
}
try{
host = InetAddress.getByName(args[0]);
port = Integer.valueOf(args[1]).intValue();
dSocket = new DatagramSocket();
BufferedReader std_in;
String userInput;
std_in = new BufferedReader(new InputStreamReader(System.in));
while ((userInput = std_in.readLine())!= null){
byte[] std_buf = userInput.getBytes();
send_dPacket = new DatagramPacket(std_buf, std_buf.length,
host, port);
dSocket.send(send_dPacket);
dPacket = new DatagramPacket(buf,buf.length);
dSocket.receive(dPacket);
System.out.println(">Echo : " + new String(dPacket.getData()).trim());
}
std_in.close();
dSocket.close();
}catch (UnknownHostException e){
System.out.println("알수 없는 호스트입니다.");
System.exit(1);
}catch (Exception e){
System.out.println("서버 종료합니다.");
}
}
}
//EchoServer_Datagram.java
import java.io.*;
import java.net.*;
public class EchoServer_Datagram{
public static void main(String[] args){
DatagramSocket dSocket;
DatagramPacket dPacket, std_dPacket;
boolean dStop = false;
try{
dSocket = new DatagramSocket(4444);
while (dStop == false){
byte[] buf = new byte[256];
dPacket = new DatagramPacket(buf,buf.length);
dSocket.receive(dPacket);
std_dPacket = new DatagramPacket(
buf,buf.length,dPacket.getAddress(), dPacket.getPort());
dSocket.send(std_dPacket);
}
dSocket.close();
}catch(Exception e){
System.out.println("서버를 종료합니다.");
}
}
}
-- Muticast IP를 이용한 채팅 프로그램
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class MulticastSocket_ChatDemo extends Frame implements Runnable{
MulticastSocket chatSocket = null;
InetAddress nGroup = null;
int nPort;
String userName = "몰라요.";
TextArea outputArea;
TextField inputField;
public MulticastSocket_ChatDemo(String title){
super(title);
setLayout(new BorderLayout());
outputArea = new TextArea();
outputArea.setEditable(false);
add(outputArea,BorderLayout.CENTER);
inputField = new TextField();
add(inputField,BorderLayout.SOUTH);
inputField.addActionListener(new InputListener());
}
public void addMessage(String msg){
outputArea.append(msg);
}
public void setup(String host_name, int port, String user_name){
try{
nGroup = InetAddress.getByName(host_name);
nPort = port;
userName = user_name;
chatSocket = new MulticastSocket(nPort);
chatSocket.joinGroup(nGroup);
}catch (IOException e){
System.err.println("호스트가 이상합니다.");
System.exit(1);
}
Thread thread = new Thread(this);
thread.start();
}
public void disconnect(){
try{
chatSocket.leaveGroup(nGroup);
chatSocket.close();
}catch (Exception e){}
}
public void run(){
try{
while (true){
byte[] buf = new byte[256];
DatagramPacket dPacket = new DatagramPacket(buf, buf.length);
chatSocket.receive(dPacket);
addMessage(new String(dPacket.getData(), "KSC5601").trim()+"n");
try{
wait(100);
}catch (Exception e){}
}
}catch (Exception e){
disconnect();
}
}
public static void main(String[] args) {
MulticastSocket_ChatDemo mscd = new MulticastSocket_ChatDemo(
"멀티캐스트 채팅");
mscd.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
mscd.pack();
mscd.setSize(300,300);
mscd.setVisible(true);
if (args.length < 3){
System.out.println("사용법n java MulticastSocket_ChatDemo 그룹_이름 포트_이름 사용자_이름");
System.exit(1);
}
mscd.setup(args[0], Integer.valueOf(args[1]).intValue(), args[2]);
}
class InputListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
byte sndbuf[] = ("[" + userName + "]" + inputField.getText()).getBytes();
inputField.setText(" ");
&n
최신글이 없습니다.
최신글이 없습니다.
댓글목록 1
재미솔솔(시니)님의 댓글
토요일날 코딩해야징.. 하하하.. 그람.. 즐 자바..