import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
//1. MalformedURLException를 이용해서 URL Parsing
public class URLDemo {
public static void main(String[] args) {
URLDemo ud = new URLDemo();
String urlStr = ud.getURL();
URL url = null;
try{
url = new URL(urlStr);
System.out.println("protocol : " + url.getProtocol());
System.out.println("hostname : " + url.getHost());
System.out.println("file : " + url.getPath() + url.getFile());
System.out.println("query string : " + url.getQuery());
System.out.println("port number : " + url.getPort());
System.out.println("default port number : " + url.getDefaultPort());
}catch(MalformedURLException ex){
System.out.println(ex.getMessage());
}
}
String getURL(){
System.out.print("URL : ");
Scanner scan = new Scanner(System.in);
return scan.next().trim();
}
}
출력:
URL : http://www.naver.com/index.html : 80
protocol : http
hostname : www.naver.com
file : /index.html/index.html
query string : null
port number : -1
default port number : 80
출력:
URL : http://software.naver.com/software/summary.nhn?softwareId=MFS_100040
protocol : http
hostname : software.naver.com
file : /software/summary.nhn/software/summary.nhn?softwareId=MFS_100040
query string : softwareId=MFS_100040
port number : -1
default port number : 80
출력:
URL : file:///home/mino/Downloads/sungjuk_utf8.dat
protocol : file
hostname :
file : /home/mino/Downloads/sungjuk_utf8.dat/home/mino/Downloads/sungjuk_utf8.dat
query string : null
port number : -1
default port number : -1
--------------------------------------------------------------
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
//2. openStream() 을 이용해서 InputStream 객체 생성
public class URLDemo1 implements ActionListener {
private JFrame f;
private JTextArea area;
private JScrollPane scroll;
private JTextField tf;
private Container con;
private URLDemo1(){
this.f = new JFrame("My Browser");
this.con = this.f.getContentPane();
this.area = new JTextArea();
this.scroll = new JScrollPane(area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.tf = new JTextField("http://", JTextField.LEFT);
this.tf.addActionListener(this);
}
private void display(){
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.con.setLayout(new BorderLayout());
this.con.add("North", this.tf);
this.con.add("Center", this.scroll);
this.f.setSize(700, 500);
this.f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent evt){
URL url = null;
BufferedReader br = null;
try{
url = new URL(this.tf.getText().trim());
InputStream is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = br.readLine()) != null){
this.area.append(line + "\n");
}
} catch(MalformedURLException ex){
JOptionPane.showMessageDialog(this.f, ex.getMessage());
} catch(IOException ex){
JOptionPane.showMessageDialog(this.f, ex.getMessage());
} finally{
try{
br.close();
} catch(IOException ex){}
}
}
public static void main(String[] args) {
new URLDemo1().display();
}
}
출력은 텍스트필드에 www.naver.com을 치면 그 화면에 html내용을 다 읽어들인다.
----------------위 코드를 파일 출력
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
//2. openStream() 을 이용해서 InputStream 객체 생성
public class URLDemo1 implements ActionListener {
private JFrame f;
private JTextArea area;
private JScrollPane scroll;
private JTextField tf;
private Container con;
private URLDemo1(){
this.f = new JFrame("My Browser");
this.con = this.f.getContentPane();
this.area = new JTextArea();
this.scroll = new JScrollPane(area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.tf = new JTextField("http://", JTextField.LEFT);
this.tf.addActionListener(this);
}
private void display(){
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.con.setLayout(new BorderLayout());
this.con.add("North", this.tf);
this.con.add("Center", this.scroll);
this.f.setSize(700, 500);
this.f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent evt){
URL url = null;
BufferedReader br = null;
PrintWriter pw = null;
try{
url = new URL(this.tf.getText().trim());
InputStream is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
String hostname = url.getHost(); //www.naver.com
hostname = hostname.substring(4, hostname.lastIndexOf("."));
pw = new PrintWriter(new BufferedWriter(new FileWriter(new File(hostname + ".txt"))));
String line = null;
while((line = br.readLine()) != null){
this.area.append(line + "\n");
pw.println(line);
pw.flush();
}
JOptionPane.showMessageDialog(this.f, "잘 저장됐습니다.");
} catch(MalformedURLException ex){
JOptionPane.showMessageDialog(this.f, ex.getMessage());
} catch(IOException ex){
JOptionPane.showMessageDialog(this.f, ex.getMessage());
} finally{
try{
br.close(); pw.close();
} catch(IOException ex){}
}
}
public static void main(String[] args) {
new URLDemo1().display();
}
}
//출력은 www.naver.com 을 치면 naver.txt로 저장됨.
----------------------------------------------------
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
//3. URL 의 openConnection() 을 이용해서 URLConnection 객체 생성
public class URLConnectionDemo {
public static void main(String[] args) {
String urlStr = new URLConnectionDemo().getURL();
URL url = null;
URLConnection conn = null;
try{
url = new URL(urlStr);
conn = url.openConnection();
Map<String, List<String>> map = conn.getHeaderFields();
Set<String> set = map.keySet();
Iterator<String> iters = set.iterator();
while(iters.hasNext()){
String key = iters.next();
System.out.print(key +" --> ");
List<String> list = map.get(key);
for(int i = 0 ; i < list.size() ; i++){
System.out.print(list.get(i) +", ");
}
System.out.println();
}
}catch(MalformedURLException ex){
}catch(IOException ex){}
}
String getURL(){
System.out.print("URL : ");
Scanner scan = new Scanner(System.in);
return scan.next().trim();
}
}
출력:
URL : http://www.naver.com
null --> HTTP/1.1 200 OK,
Vary --> Accept-Encoding,User-Agent,
Transfer-Encoding --> chunked,
Date --> Wed, 02 Apr 2014 01:39:17 GMT,
P3P --> CP="CAO DSP CURa ADMa TAIa PSAa OUR LAW STP PHY ONL UNI PUR FIN COM NAV INT DEM STA PRE",
Connection --> close,
Content-Type --> text/html; charset=UTF-8,
Server --> nginx,
Pragma --> no-cache,
Cache-Control --> no-cache, no-store, must-revalidate,
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
URL Encoder
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Scanner;
public class URLEncoderDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = new URLEncoderDemo().getString();
String en = URLEncoder.encode(str, "KSC5601");
System.out.printf("%s --> %s\n", str, en);
}
String getString(){
System.out.print("Encoding 할 문자열 : ");
Scanner scan = new Scanner(System.in);
return scan.next().trim();
}
}
출력:
Encoding 할 문자열 : 안녕하세요
안녕하세요 --> %BE%C8%B3%E7%C7%CF%BC%BC%BF%E4
-----------------------------------------
URL Decoder
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Scanner;
public class URLDecoderDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = new URLDecoderDemo().getString();
String de = URLDecoder.decode(str, "KSC5601");
System.out.printf("%s --> %s\n", str, de);
}
String getString(){
System.out.print("Decoding 할 문자열 : ");
Scanner scan = new Scanner(System.in);
return scan.next().trim();
}
}
출력:
Decoding 할 문자열 : %BE%C8%B3%E7%C7%CF%BC%BC%BF%E4
%BE%C8%B3%E7%C7%CF%BC%BC%BF%E4 --> 안녕하세요
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
TCP
Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpDemo {
private ServerSocket server;
private Socket client;
private TcpDemo(){
this.server = null;
try{
this.server = new ServerSocket(8080);
System.out.println("Server is just started...");
}catch(IOException ex){
System.out.println(ex.getMessage());
}
}
private void service(){
BufferedReader br = null;
try{
this.client = this.server.accept();
System.out.println("[" + this.client.getInetAddress().getHostAddress() + "] 접속성공");
InputStream is = this.client.getInputStream();
String line = null;
br = new BufferedReader(new InputStreamReader(is));
while((line = br.readLine()) != null){
System.out.println(line);
}
}catch(IOException ex){
System.out.println(ex.getMessage());
}finally{
try{
this.client.close();
br.close();
}catch(IOException ex){}
}
}
public static void main(String[] args) {
new TcpDemo().service();
}
}
//쓰레드를 안만들어서 동시성이없다. 쓰레드를 만들어야함.
출력: 웹페이지에서 http://localhost:8080 입력. or http://Ubuntu-22:8080 (Ubuntu-22는 내 컴퓨터이름)
Server is just started...
[127.0.0.1] 접속성공
GET / HTTP/1.1
Host: ubuntu-22:8080
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
출력: 웹페이지에서 http://localhost:8080/abc/def/ghi.test.html 입력.
Server is just started...
[127.0.0.1] 접속성공
GET /abc/def/ghi.test.html HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
//접속해서 들어온 클라이언트의 정보를 알 수 있다. 크롬으로 접속했으며등등~~
--------------------------------내보낼때
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpDemo {
private ServerSocket server;
private Socket client;
private TcpDemo(){
this.server = null;
try{
this.server = new ServerSocket(8080);
System.out.println("Server is just started...");
}catch(IOException ex){
System.out.println(ex.getMessage());
}
}
private void service(){
BufferedReader br = null;
PrintWriter pw = null;
try{
this.client = this.server.accept();
System.out.println("[" + this.client.getInetAddress().getHostAddress() + "] 접속성공");
InputStream is = this.client.getInputStream();
String line = null;
br = new BufferedReader(new InputStreamReader(is));
line = br.readLine(); //GET /index.html HTTP/1.1
int start = line.indexOf(" "); //3
int last = line.lastIndexOf("HTTP"); //16
line = line.substring(start +2, last); //index.html 만 뽑기 위해서
String filename = null;
if(line.length() == 1) filename = "index.html";
else filename = line;
//System.out.println(filename);
OutputStream os = this.client.getOutputStream(); //client로 전송할 객체
File file = new File(filename);
pw = new PrintWriter(new OutputStreamWriter(os));
br = null;
br = new BufferedReader(new FileReader(file));
line = null;
while((line = br.readLine()) != null){ //index.html파일로부터 읽기
pw.println(line);
pw.flush();
}
while(line = p)
}catch(IOException ex){
System.out.println(ex.getMessage());
}finally{
try{
this.client.close();
br.close();
pw.close();
}catch(IOException ex){}
}
}
public static void main(String[] args) {
new TcpDemo().service();
}
}
그리고 다른컴퓨터에서 html파일로 아래와 같이 만들어서 이름을 index.html 로 주고 tcp.class와 같은 폴더에 저장한다.
<html>
<head>
<meta charset="UTF-8">
<title>Welcome! my hompage...</title>
</head>
<body bgcolor='yellow'>
<font size='7' color='red'><b>Hello, World</font>
</body>
</html>
실행시키면 노랑바탕에 빨강 글씨로 나온다.
그리고 서버를 열고.....
이제 내컴퓨터에서 웹페이지에서 접속할 아이피:8080 을 쓰면 index.html 페이지가 열린다
---------------------------------------------------------------
쓰레드까지 추가. 그러면 여러번 한번접속후 종료하지않고 계속 받을 수 있음.
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Apache {
private ServerSocket server;
private Socket client;
Apache(){
try{
this.server = new ServerSocket(8081);
System.out.println("Server is ready...");
while(true){
this.client = this.server.accept();
ClientThread ct = new ClientThread(this.client);
ct.start();
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
new Apache();
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class ClientThread extends Thread {
private Socket client;
private BufferedReader br;
private PrintWriter pw;
ClientThread(Socket client){
this.client = client;
try {
InputStream is = this.client.getInputStream();
OutputStream os = this.client.getOutputStream();
this.br = new BufferedReader(new InputStreamReader(is));
this.pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os)));
} catch (Exception e) {
System.out.println(e.toString());
}
}
@Override
public void run(){
//Thread 가 해야할 일
try{
String line = this.br.readLine(); //GET /index.html HTTP/1.1
int start = line.indexOf(" "); //3
int last = line.lastIndexOf("HTTP"); //16
line = line.substring(start + 2, last); //index.html
String filename = null;
if(line.length() == 1) filename = "index.html";
else filename = line;
//파일을 읽을 BufferedReader
BufferedReader brTemp =
new BufferedReader(new FileReader(new File(filename)));
line = null;
while((line = brTemp.readLine()) != null){ //파일로 부터 한 줄씩 읽어서
this.pw.println(line);
this.pw.flush();
}
brTemp.close();
}catch(Exception ex){
ex.printStackTrace();
}finally{
try{
if(this.br != null) this.br.close();
if(this.pw != null) this.pw.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
TCP 서버 클라이언트 : 잘 전송되는지 확인.
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
private ServerSocket server;
private Socket client;
private BufferedReader br;
private PrintWriter pw;
private TcpServer(){
try{
this.server = new ServerSocket(8888);
System.out.println("Server is ready...");
}catch(Exception ex){
ex.printStackTrace();
}
}
private void service(){
try{
while(true){
this.client = this.server.accept();
System.out.println(
"[" + this.client.getInetAddress().getHostAddress() + "] 님이 연결됐습니다." );
TcpThread tt = new TcpThread(this.client);
tt.start();
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
System.out.println("Server is closed...");
try{
this.server.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new TcpServer().service();
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class TcpThread extends Thread{
private Socket client;
private BufferedReader br;
private PrintWriter pw;
TcpThread(Socket client){
this.client = client;
try{
this.br = new BufferedReader(
new InputStreamReader(this.client.getInputStream()));
this.pw = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(this.client.getOutputStream())));
}catch(Exception ex){
ex.printStackTrace();
}
}
@Override
public void run(){
//Thread 가 해야할 일
try{
String line = null;
while(true){
line = this.br.readLine();
if(line.equals("quit")) break;
System.out.println("String from Client : " + line);
this.pw.println(line);
this.pw.flush();
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
try{
this.br.close();
this.pw.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class TcpClient {
private Socket socket;
private Scanner scan;
private String ip;
private int port;
private BufferedReader br;
private PrintWriter pw;
TcpClient(){
try{
this.scan = new Scanner(System.in);
this.getServerInfo();
this.socket = new Socket(ip, port);
System.out.println("[" + this.ip + "] connected...");
this.br = new BufferedReader(
new InputStreamReader(this.socket.getInputStream()));
this.pw = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(this.socket.getOutputStream())));
}catch(Exception ex){
ex.printStackTrace();
}
}
private void service(){
try{
String line = null;
while(true){
System.out.print("서버에 보낼 문자열 : ");
line = this.scan.nextLine().trim();
if(line == null || line.equals("quit")) {
this.pw.println("quit");
this.pw.flush();
break;
}
this.pw.println(line);
this.pw.flush(); //서버로 발송
System.out.println("서버로 부터 들어온 문자열 : " + this.br.readLine());
//서버에서 들어온 문자열
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
try{
this.br.close();
this.pw.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
TcpClient tc = new TcpClient();
tc.service();
}
void getServerInfo(){
System.out.print("Server IP : "); this.ip = this.scan.nextLine();
System.out.print("Server Port Number : "); this.port = this.scan.nextInt();
this.scan.nextLine(); //enter key 날리자.
}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
채팅
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
public class ChatServer {
private ServerSocket server;
private Socket client;
ChatServer(){ //constructor
try{
this.server = new ServerSocket(9999);
System.out.println("Chatting Server is ready...");
Hashtable<String, PrintWriter> ht = new Hashtable<String, PrintWriter>();
while(true){
this.client = this.server.accept();
ChatServerThread cst = new ChatServerThread(this.client, ht);
cst.start();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void main(String[] args) {
new ChatServer();
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
public class ChatServerThread extends Thread {
private Socket client;
private Hashtable<String, PrintWriter> ht;
private String id; //대화명
private BufferedReader br;
private PrintWriter pw;
public ChatServerThread(Socket client, Hashtable<String, PrintWriter> ht) {
this.client = client;
this.ht = ht;
try{
this.br = new BufferedReader(
new InputStreamReader(this.client.getInputStream()));
this.pw = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
this.client.getOutputStream())));
this.id = br.readLine(); //사용자의 아이디
synchronized(this.ht){
System.out.println("[" + this.id + "]님이 입장하셨습니다.");
this.ht.put(this.id, this.pw);
this.broadcast("[" + this.id + "]님이 입장하셨습니다.");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
@Override
public void run(){
//Thread 가 해야할 일
try{
String line = null;
while((line = this.br.readLine()) != null){
if(line.equals("quit")) break;
this.broadcast("[" + this.id +"]" + line);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
synchronized(this.ht){
this.ht.remove(this.id);
}
this.broadcast("[" + this.id + "] 님이 퇴장하셨습니다.");
try{
if(this.br != null) this.br.close();
if(this.pw != null) this.pw.close();
if(this.client != null) this.client.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
private void broadcast(String msg){
synchronized(this.ht){
Collection<PrintWriter> members = this.ht.values();
Iterator<PrintWriter> iters = members.iterator();
while(iters.hasNext()){
PrintWriter pw1 = iters.next();
pw1.println(msg);
pw1.flush();
}
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
private Socket client;
private String id;
private String ip;
private int port;
private Scanner scan;
private BufferedReader br;
private PrintWriter pw;
ChatClient(){
this.scan = new Scanner(System.in);
getServerInfo();
try{
this.client = new Socket(this.ip, this.port);
this.br = new BufferedReader(
new InputStreamReader(this.client.getInputStream()));
this.pw = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
this.client.getOutputStream())));
this.pw.println(this.id); //서버에접속하면 가장먼저 아이디를 읽으므로, 클라이언트에서는 제일 먼저 아이디를 보내줘야 한다.
this.pw.flush();
ChatClientThread cct = new ChatClientThread(this.client, this.br); //서버로 부터 문자열을 받을 객체
cct.start();
}catch(Exception ex){
ex.printStackTrace();
}
}
private void getServerInfo(){
System.out.print("대화명 : "); this.id = this.scan.nextLine();
System.out.print("서버IP : "); this.ip = this.scan.nextLine();
System.out.print("서버 Port Number : "); this.port = this.scan.nextInt();
this.scan.nextLine(); //마지막 엔터키 처리
}
private void service(){ //채팅서버로 문자열을 보내는 메소드
while(true){
System.out.print("[" + this.id + "] >> ");
String line = this.scan.nextLine();
if(line == null || line.equals("quit")){
this.pw.println("quit"); //서버에도 quit라고 보내고
this.pw.flush();
break;
}
this.pw.println(line); this.pw.flush();
}
}
public static void main(String[] args) {
new ChatClient().service();
}
}
import java.awt.BorderLayout;
import java.awt.Container;
import java.io.BufferedReader;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ChatClientThread extends Thread {
private Socket client;
private BufferedReader br;
private JFrame f;
private JTextArea area;
private Container con;
private JScrollPane pane;
public ChatClientThread(Socket client, BufferedReader br) {
this.client = client;
this.br = br;
this.f = new JFrame("Chatting Window");
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.con = this.f.getContentPane();
this.con.setLayout(new BorderLayout());
this.area = new JTextArea();
this.pane = new JScrollPane(this.area, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
this.con.add("Center", this.pane);
this.f.setSize(700, 400);
this.f.setVisible(true);
}
@Override
public void run(){ //서버가 보내준 문자열을 받는 메소드
try{
String line = null;
while((line = this.br.readLine()) != null){
this.area.append(line + "\n");
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
try{
if(this.client != null) this.client.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
}
ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
http://www.ubuntu.com/ 이동
Download-Desktop 이동. Ubuntu 13.10 64비트 버전 다운. 후
VMware Workstation에 설치
'Java & Oracle' 카테고리의 다른 글
자바 ODBC설정, 성적관리프로그램(db와연결,스윙), 전화요금관리프로그램(찾기기능없음,스윙x,콘솔창으로) (0) | 2014.04.04 |
---|---|
자바 UDP, NIO와IO속도측정, JDBC 시작(설정) (0) | 2014.04.03 |
File, 탐색기, 직렬화, java.net( InetAddress), Vmware Workstation으로 윈도우 깔기(한글 적용, Ubuntu 한글 적용) (0) | 2014.04.01 |
자바 I/O (RandomAccess까지) (0) | 2014.03.31 |
자바 Thread , 열차예매프로그램 (0) | 2014.03.28 |