1
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerEx01 {
public static void main(String[] args) {
// 서버만들기
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(7777);
System.out.println("서버가 준비되었습니다.");
socket = serverSocket.accept();
System.out.println("클라이언트와 연결되었습니다.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
}
}
}
--cmd 창에서 서버오픈하기
cd c:\java\workspace\NetworkEx02\bin
java TcpServerEx01
서버준비 상태에서 다시 같은 서버를 오픈 하려고하면 에러남
2. 이클립스에서 서버와 클라이언트 둘다 실행 못함. 서버는 cmd에서 실행시킴
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientEx01 {
public static void main(String[] args) {
// 특정 컴퓨터에 접속하기
Socket socket = null;
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777); //자신의 IP//서버쪽 포트를 적어줌 //클라이언트 포트는 랜덤하게 열림
System.out.println("서버와 연결되었습니다.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(socket != null) try{ socket.close();} catch(IOException e){}
}
}
}
클라이언트 접속 클래스를 실행시킬 경우 서버대기상태 → 연결되었습니다로 바뀜
3
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerEx01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
BufferedWriter bw = null; //서버쪽에서 클라이언트에게 글자보내기
try {
serverSocket = new ServerSocket(7777);
System.out.println("서버가 준비되었습니다.");
socket = serverSocket.accept();
System.out.println("클라이언트와 연결되었습니다.");
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("Hello Socket" + "\n"); //엔터키를 넣어야지 클라이언트쪽에서 읽을 수 있슴
bw.flush(); //버퍼 데이터를 비움
System.out.println("전송이 완료되었습니다.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientEx01 {
public static void main(String[] args) {
// 특정 컴퓨터에 접속하기
Socket socket = null;
BufferedReader br = null; //서버로부터 글자 읽어오기
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("서버에서 보낸 글씨 : " + br.readLine()); //readLine 엔터키까지 읽음
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null) try{ socket.close();} catch(IOException e){}
if(br != null) try{ br.close();} catch(IOException e){}
}
}
}
4. 반대로 클라이언트가 정보를 보낼 수 있음
//서버
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerEx01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader br = null; //서버쪽에서 클라이언트 읽기
try {
serverSocket = new ServerSocket(7777);
System.out.println("서버가 준비되었습니다.");
socket = serverSocket.accept();
System.out.println("클라이언트와 연결되었습니다.");
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("클라이언트에서 보낸 글씨 : " + br.readLine()); //readLine 엔터키까지 읽음
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
if(br != null) try{ br.close();} catch(IOException e){}
}
}
}
//클라이언트
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientEx01 {
public static void main(String[] args) {
// 특정 컴퓨터에 접속하기
Socket socket = null;
BufferedWriter bw = null; //서버로 글자 보내기
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("Hello Socket" + "\n"); //엔터키를 넣어야지 서버에서 readline으로 읽을 수 있슴
bw.flush(); //버퍼 데이터를 비움
System.out.println("전송이 완료되었습니다.");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null) try{ socket.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
}
}
}
5
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerEx01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader br = null; //서버, 클라이언트 양방향 읽기, 쓰기
BufferedWriter bw = null;
try {
serverSocket = new ServerSocket(7777);
System.out.println("서버가 준비되었습니다.");
socket = serverSocket.accept();
System.out.println("클라이언트와 연결되었습니다.");
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
//utf-8 설정가능
bw.write(br.readLine()+"\n"); //클라이언트에서 보낸 글자를 다시 클라이언트에게 보냄
bw.flush();
System.out.println("전송완료");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
if(br != null) try{ br.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientEx01 {
public static void main(String[] args) {
// 특정 컴퓨터에 접속하기
Socket socket = null;
BufferedWriter bw = null; //양방향 읽기, 쓰기
BufferedReader br = null;
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
//utf-8 설정가능
bw.write("안녕한글" + "\n"); //서버에 메시지 보냄
bw.flush();
System.out.println("전송이 완료되었습니다.");
System.out.println("메시지 : "+ br.readLine()); //서버로 부터 메시지 받음
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null) try{ socket.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
if(br != null) try{ br.close();} catch(IOException e){}
}
}
}
6
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerEx01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader br = null;
try {
serverSocket = new ServerSocket(7777);
System.out.println("서버가 준비되었습니다.");
socket = serverSocket.accept();
System.out.println("클라이언트와 연결되었습니다.");
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
//클라이언트에서 여러줄 보낸 것을 모두 읽어 드림
String msg = null;
while((msg = br.readLine()) != null){
System.out.println("클라이언트에서 보낸 글씨 : " + msg);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
if(br != null) try{ br.close();} catch(IOException e){}
}
}
}
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientEx01 {
public static void main(String[] args) {
// 특정 컴퓨터에 접속하기
Socket socket = null;
BufferedWriter bw = null; //서버로부터 글자 읽어오기
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
bw.write("안녕 한글1" + "\n");
bw.write("안녕 한글2" + "\n");
bw.write("안녕 한글3" + "\n");
bw.write("안녕 한글4" + "\n");
bw.write("안녕 한글5" + "\n");
bw.flush(); //버퍼 데이터를 비움
System.out.println("전송이 완료되었습니다.");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null) try{ socket.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
}
}
}
7
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.SpringLayout.Constraints;
public class TcpServerEx01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader br = null; //서버쪽에서 클라이언트 읽기
BufferedWriter bw = null; //서버쪽에서 보내기
try {
serverSocket = new ServerSocket(7777);
System.out.println("서버가 준비되었습니다.");
socket = serverSocket.accept();
System.out.println("클라이언트와 연결되었습니다.");
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
//utf-8 설정가능
//클라이언트가 보낸 여러줄의 메시지를 읽고 다시 클라이언트에게 보냄
String msg = null;
//while((msg = br.readLine()) != null){ //무한루프에 빠질 수 있음
//클라이언트와 연결이 종료되어야지 서버가br로 읽을때 null값을 가짐
//그러나 클라이언트의 bw 코드뒤에 br이 있어서 통신이 종료되는 finally 까지 진행되지 않음
while(!(msg = br.readLine()).contains("exit")){
bw.write(msg+"\n");
}
bw.flush();
System.out.println("전송완료");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(br != null) try{ br.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientEx01 {
public static void main(String[] args) {
// 특정 컴퓨터에 접속하기
Socket socket = null;
BufferedWriter bw = null; //서버로부터 글자 읽어오기
BufferedReader br = null;
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
//utf-8 설정가능
bw.write("안녕한글1" + "\n"); //서버에 메시지 보냄
bw.write("안녕한글2" + "\n");
bw.write("안녕한글3" + "\n");
bw.write("안녕한글4" + "\n");
bw.write("안녕한글5" + "\n");
bw.write("exit \n"); //종료코드 보냄
bw.flush();
System.out.println("전송이 완료되었습니다.");
//서버로 부터 여러줄 메시지 받음
String msg = null;
while((msg = br.readLine()) != null){
System.out.println("메시지 : "+ msg);
}
System.out.println("모든 메시지를 전송 받았습니다.");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) try{ br.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
}
}
}
8
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.SpringLayout.Constraints;
public class TcpServerEx01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader br = null; //서버쪽에서 클라이언트 읽기
BufferedWriter bw = null; //서버쪽에서 보내기
try {
serverSocket = new ServerSocket(7777);
System.out.println("서버가 준비되었습니다.");
socket = serverSocket.accept();
System.out.println("클라이언트와 연결되었습니다.");
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
//클라이언트가 보낸 구구단 단수를 읽음 //숫자로 형변환
int start = Integer.parseInt(br.readLine());
int end = Integer.parseInt(br.readLine());
//구구단만들어 보냄
for(int i = start; i<=end; i++){
String result= "";
for(int j = 1; j<10; j++){
result += i+"*"+j+" = "+i*j+" \t";
}
result += "\n";
bw.write(result);
}
bw.flush();
System.out.println("전송완료");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(br != null) try{ br.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
}
}
}
//클라이언트에서 구구단 단수를 입력해서 서버로부터 구구단 결과값 받기
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TcpClientEx01 {
public static void main(String[] args) {
// 클라이언트
Socket socket = null;
BufferedWriter bw = null;
BufferedReader br = null;
//구구단 시작단수 와 끝단수를 입력 받음
Scanner scan = new Scanner(System.in);
System.out.println("시작단수: ");
String start = scan.next();
System.out.println("끝단수: ");
String end = scan.next();
scan.close();
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
//utf-8 설정가능
bw.write(start + "\n"); //서버에 시작단수 끝단수 보냄
bw.write(end + "\n");
bw.flush();
System.out.println("전송이 완료되었습니다.");
//서버로 부터 여러줄 메시지 받음
String msg = null;
while((msg = br.readLine()) != null){
System.out.println("메시지 : "+ msg);
}
System.out.println("모든 메시지를 전송 받았습니다.");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) try{ br.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
}
}
}
9
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerEx01 {
public static void main(String[] args) {
// 서버를 종료하지 않고 무한루프
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(7777);
while (true) {
try {
System.out.println("서버가 준비되었습니다");
socket = serverSocket.accept(); //멈추는 부분
System.out.println("클라이언트와 연결되었습니다.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(socket != null) try{ socket.close();} catch(IOException e){}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientEx01 {
public static void main(String[] args) {
// 클라이언트
Socket socket = null;
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null) try{ socket.close();} catch(IOException e){}
}
}
}
10
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerEx01 {
public static void main(String[] args) {
// 서버를 종료하지 않고 무한루프 //클라이언트와 입출력 처리할 수있음
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
serverSocket = new ServerSocket(7777);
while (true) {
try {
System.out.println("서버가 준비되었습니다");
socket = serverSocket.accept(); //멈추는 부분
System.out.println("클라이언트와 연결되었습니다.");
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
bw.write(br.readLine() + "\n"); //클라이언트로 입력을 받아서 다시 보냄
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(socket != null) try{ socket.close();} catch(IOException e){}
if(br != null) try{ br.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpClientEx01 {
public static void main(String[] args) {
// 클라이언트
Socket socket = null;
BufferedWriter bw = null;
BufferedReader br = null;
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
//utf-8 설정가능
bw.write("안녕한글1" + "\n"); //서버에 메시지 보냄
bw.flush();
System.out.println("전송이 완료되었습니다.");
System.out.println("메시지 : " +br.readLine());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null) try{ socket.close();} catch(IOException e){}
if(br != null) try{ br.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
}
}
}
11
//구구단 서버 무한루프
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.SpringLayout.Constraints;
public class TcpServerEx01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
BufferedReader br = null; //서버쪽에서 클라이언트 읽기
BufferedWriter bw = null; //서버쪽에서 보내기
try {
serverSocket = new ServerSocket(7777);
while(true){
try {
System.out.println("서버가 준비되었습니다.");
socket = serverSocket.accept();
System.out.println("클라이언트와 연결되었습니다.");
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
//클라이언트가 보낸 구구단 단수를 읽음 //숫자로 형변환
int start = Integer.parseInt(br.readLine());
int end = Integer.parseInt(br.readLine());
//구구단만들어 보냄
for(int i = start; i<=end; i++){
String result= "";
for(int j = 1; j<10; j++){
result += i+"*"+j+" = "+i*j+" \t";
}
result += "\n";
bw.write(result);
}
bw.flush();
System.out.println("전송완료");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(br != null) try{ br.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
}
}
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
if(serverSocket != null) try{ serverSocket.close();} catch(IOException e){}
}
}
}
//클라이언트 요청은 위와 동일
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TcpClientEx01 {
public static void main(String[] args) {
// 클라이언트
Socket socket = null;
BufferedWriter bw = null;
BufferedReader br = null;
//구구단 시작단수 와 끝단수를 입력 받음
Scanner scan = new Scanner(System.in);
System.out.println("시작단수: ");
String start = scan.next();
System.out.println("끝단수: ");
String end = scan.next();
scan.close();
try {
System.out.println("서버와 연결 중입니다.");
socket = new Socket("localhost", 7777);
System.out.println("서버와 연결되었습니다.");
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
//utf-8 설정가능
bw.write(start + "\n"); //서버에 시작단수 끝단수 보냄
bw.write(end + "\n");
bw.flush();
System.out.println("전송이 완료되었습니다.");
//서버로 부터 여러줄 메시지 받음
String msg = null;
while((msg = br.readLine()) != null){
System.out.println("메시지 : "+ msg);
}
System.out.println("모든 메시지를 전송 받았습니다.");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) try{ br.close();} catch(IOException e){}
if(bw != null) try{ bw.close();} catch(IOException e){}
if(socket != null) try{ socket.close();} catch(IOException e){}
}
}
}
12
//채팅 서버 만들기
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
public class ChatServer {
//클라이언트의 집합을 관리할 컬렉션 만듦
private HashMap<String, BufferedWriter> clients; //id, 얘기 통로 가지고옴
public static void main(String args[]) {
// TODO Auto-generated method stub
new ChatServer().start();
}
public ChatServer() {
clients = new HashMap<String, BufferedWriter>();
//Collections.synchronizedMap(clients); //동기화 기능
}
public void start() {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(7777);
System.out.println("서버가 시작되었습니다.");
while(true) {
socket = serverSocket.accept();//클라이언트를 받아들여 소켓을 만듦
ServerReceiver thread = new ServerReceiver(socket); //소켓을 쓰레드로 처리함 //클라이언트 하나당 쓰레드 하나 만듦
thread.start();
}
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sendToAll(String msg) { //모든 클라이언트에게 메세지를 보내는 함수를 생성
Iterator<String> it = clients.keySet().iterator(); //iterator 컬렉션안의 데이터를 하나씩 뽑아냄
while(it.hasNext()) {
try {
BufferedWriter bw = (BufferedWriter)clients.get(it.next()); //해쉬맵에 저장된 클라이언트 각각의 소캣연결 bufferedWriter 가져옴
bw.write(msg + System.getProperty("line.separator")); //System.getProperty 엔터키
bw.flush();
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ServerReceiver extends Thread { //스레드를 통해서 클라이언트 읽기와 쓰기가 가능해짐
private Socket socket;
private BufferedReader br;
private BufferedWriter bw;
public ServerReceiver(Socket socket) { //클라이언트 각각의 연결소켓을 매개변수로 받음
this.socket = socket;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
String name = "";
try {
name = br.readLine();
sendToAll("#" + name + "님이 들어오셨습니다.");
clients.put(name, bw);
System.out.println("현재 서버접속자 수는 " + clients.size() + "입니다.");
while(br != null) { //무한루프 //클라이언트와 접속이 끊어질때 까지 무한히 반복함
sendToAll(br.readLine());
}
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
sendToAll("#" + name + "님이 나가셨습니다.");
clients.remove(name);
System.out.println("현재 서버접속자 수는 " + clients.size() + " 입니다.");
}
}
}
}
//채팅 클라이언트 만들기
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.Socket;
public class ChatClient {
public static void main(String args[]) { //클라이언트의 id를 매개변수로 받음
// TODO Auto-generated method stub
if(args.length != 1) {
System.out.println("USAGE: java ChatClient 대화명");
System.exit(0);
}
try {
Socket socket = new Socket("localhost", 7777); //소켓을 생성
System.out.println("서버에 연결되었습니다.");
Thread sender = new Thread(new ClientSender(socket, args[0])); //new ClientSender(socket, args[0]) 상속받았으므로 쓰래드를 생성안해도 됨 //Thread를 생성하는 것은 런어블 방식
Thread receiver = new Thread(new ClientReceiver(socket));
sender.start(); //sender와 receiver 쓰레드를 따로 만듦 //sender에서 작업을 수행하는 중간에도 receiver로 받기위함
receiver.start();
} catch(ConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static class ClientSender extends Thread {
private Socket socket;
private BufferedWriter bw;
private String name;
public ClientSender(Socket socket, String name) {
this.socket = socket;
try {
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
this.name = name;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in)); //콘솔창의 입력값을 받을 스트림을 만듦
if(bw != null) {
bw.write(name + System.getProperty("line.separator")); //클라이언트 아이디를 먼저 1회 보냄
bw.flush();
}
while(bw != null) { //대화 내용은 무한루프 //서버와 연결이 끊길때까지 무한히 반복함
String msg =br.readLine(); //여기서 정지하고 있음 //콘솔창에서 입력되면 다음으로 넘어감
bw.write("[" + name + "]" + msg + System.getProperty("line.separator"));
bw.flush();
}
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (br != null) try { br.close(); } catch(IOException e) {}
}
}
}
static class ClientReceiver extends Thread {
private Socket socket;
private BufferedReader br;
public ClientReceiver(Socket socket) {
this.socket = socket;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
while(br != null) {
try {
String msg = br.readLine();
System.out.println(msg);
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
13
//클라이언트에서 종료코드를 입력하면 무한루프에서 빠져나오도록 서버 설정
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Iterator;
public class ChatServer {
private HashMap<String, BufferedWriter> clients;
public static void main(String args[]) {
// TODO Auto-generated method stub
new ChatServer().startServer();
}
public ChatServer() {
clients = new HashMap<String, BufferedWriter>();
}
public void startServer() {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(7777);
System.out.println("서버가 시작되었습니다.");
while(true) {
socket = serverSocket.accept();
ServerReceiver thread = new ServerReceiver(socket);
thread.start();
}
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ServerReceiver extends Thread {
private Socket socket;
private BufferedReader br;
private BufferedWriter bw;
public ServerReceiver(Socket socket) {
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sendToAll(String msg) {
Iterator<String> it = clients.keySet().iterator();
while(it.hasNext()) {
try {
BufferedWriter bw = (BufferedWriter)clients.get(it.next());
bw.write(msg + System.getProperty("line.separator"));
bw.flush();
} catch(IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
}
public void run() {
String name = "";
try {
name = br.readLine();
sendToAll("#" + name + "님이 들어오셨습니다.");
clients.put(name, bw);
System.out.println("현재 서버접속자 수는 " + clients.size() + "입니다.");
String msg = null;
while((msg = br.readLine()) != null) {
if(msg.endsWith("나가기")) {
break;
}
sendToAll(msg);
}
} catch(IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} finally {
sendToAll("#" + name + "님이 나가셨습니다.");
clients.remove(name);
System.out.println("현재 서버접속자 수는 " + clients.size() + " 입니다.");
if(br != null) try { br.close(); } catch(IOException e) {}
if(bw != null) try { bw.close(); } catch(IOException e) {}
if(socket != null) try { socket.close(); } catch(IOException e) {}
}
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.Socket;
public class ChatClient {
public static void main(String args[]) {
// TODO Auto-generated method stub
if(args.length != 1) {
System.out.println("USAGE: java ChatClient 대화명");
System.exit(0);
}
try {
Socket socket = new Socket("localhost", 7777);
System.out.println("서버에 연결되었습니다.");
Thread sender = new Thread(new ClientSender(socket, args[0]));
Thread receiver = new Thread(new ClientReceiver(socket, args[0]));
sender.start();
receiver.start();
} catch(ConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static class ClientSender extends Thread {
private Socket socket;
private BufferedWriter bw;
private String name;
public ClientSender(Socket socket, String name) {
this.socket = socket;
try {
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
this.name = name;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
if(bw != null) {
bw.write(name + System.getProperty("line.separator"));
bw.flush();
}
while(bw != null) {
String msg = br.readLine();
bw.write("[" + name + "]" + msg + System.getProperty("line.separator"));
bw.flush();
if(msg.equals("나가기")) {
break;
}
}
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(br != null) try { br.close(); } catch(IOException e) {}
if(bw != null) try { bw.close(); } catch(IOException e) {}
if(socket != null) try { socket.close(); } catch(IOException e) {}
}
}
}
static class ClientReceiver extends Thread {
private Socket socket;
private BufferedReader br;
private String name;
public ClientReceiver(Socket socket, String name) {
this.socket = socket;
this.name = name;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
try {
while(br != null) {
String msg = br.readLine();
System.out.println(msg);
if(msg.equals("#" + name + "님이 나가셨습니다.")) {
break;
}
}
} catch(IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} finally {
if(br != null) try { br.close(); } catch(IOException e) {}
if(socket != null) try { socket.close(); } catch(IOException e) {}
}
}
}
}
댓글 없음:
댓글 쓰기