간단한 서버/클라이언트
----- server -----
import java.net.*;
import java.io.*;
class EchoServer
{
public static void main(String[] args)
{
try{
ServerSocket ss = new ServerSocket(5555);
System.out.println("Client 접속 대기중 .....");
Socket s= ss.accept();
System.out.println("연결 되었습니다.");
BufferedReader in= new BufferedReader(new InputStreamReader
(s.getInputStream()));
OutputStream out = s.getOutputStream();
String inputMessage; // 클라이언트의 메세지
String name = in.readLine(); // 대화명
while((inputMessage = in.readLine()) != null)
{
System.out.println(inputMessage);
out.write(("[["+name+"]] "+inputMessage+"\n").getBytes());
}
}catch(Exception e)
{
System.out.println("Client접속 실패:"+e);
e.printStackTrace();
}
}//main
}//class
----- client -----
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
class ChatClient extends Frame implements ActionListener, Runnable
{
TextArea ta;
TextField tf;
List list;
Button bt_exit;
Panel p;
Socket s;
InputStream in;
OutputStream out;
BufferedReader br;
String name;
ChatClient(String h)
{
ta = new TextArea();
tf = new TextField();
list = new List();
bt_exit = new Button("Exit");
p = new Panel();
p.setLayout(new BorderLayout());
p.add("Center",tf);
p.add("East",bt_exit);
p.add("West",new Label("Messgae :"));
setLayout(new BorderLayout(5,5));
add("Center",ta);
add("East",list);
add("South",p);
setSize(400,400);
setVisible(true);
name = JOptionPane.showInputDialog(this,"대화명"); //대화상자 생성
tf.addActionListener(this);
bt_exit.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
connProcess(h); // 서버에 접속하는 함수 호출
new Thread(this).start(); // 쓰레드 시작
}//constructor
void connProcess(String host)
{
try{
s = new Socket(host,5555); // 서버에 연결
System.out.println("Connect to Server !");
out = s.getOutputStream();
in = s.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
out.write((name+"\n").getBytes()); //입력받은 대화명을 서버로 보냄
}catch(Exception e)
{
System.out.println("서버접속 실패"+e);
e.printStackTrace();
}
}// connProcess
public void run()
{
while(true)
{
try
{
String msg = br.readLine(); // msg로 서버로부터 읽어온 데이터를 넣는다.
if(msg == null)
{
return;
}
ta.append(msg+"\n"); // 읽어온 데이터를 출력
}
catch(IOException ea)
{
System.out.println("서버로부터 데이터 가져오기 실패"+ea);
}
}//while
}// run
void sendProcess()
{
try
{
String sendmsg = tf.getText(); //TextField에서 문자열을 읽어와 sendmsg에저장
if(sendmsg.length() > 0 )
{
out.write((sendmsg+"\n").getBytes()); //서버로 데이터 전송
}
else
{
return;
}
tf.setText(null);
}catch(Exception ex)
{
System.out.println("접속 끊김"+ex);
ex.printStackTrace();
}
}// sendProcess
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == tf)
{
sendProcess();
}else if(e.getSource() == bt_exit)
{
System.exit(0);
}
}// actionPerformed
public static void main(String[] args)
{
new ChatClient(args[0]);
}//main
}// class