본문 바로가기
CLASS/JAVA

#16-2 / 서버 - TCP

by eungSe__ 2024. 5. 23.

해당 기능 제작시 무조건 서버 먼저 제작 -> 클라이언트 제작해야함

 

1. s : 내 서버 구축(port번호 정해서 socket open -> cmd로 열렸나 확인)

2. cclient에서 접근 : Socket sk = new Socket(ip,port);

3. c : OutputStream os = sk.getOutputStream : 클라이언트 -> 서버로 전송하는 역할

4. s : InputStream is = sk.getInputStream : 클라이언트에서 적용된 메세지를 받는 역할

  

⚡ 네트워크 url 정보 현황

해당 페이지 크롤링 되어서 html파일 생성
public static void main(String[] args) {
        String url = "https://nain.co.kr/shop/member.html";
        try {
            URL u = new URL(url);
            URLConnection con = u.openConnection(); //해당 경로 연결

            System.out.println(u.getProtocol()); //https 출력
            System.out.println(u.getPort()); //-1 : 포트번호 ~.co.kr:443/shop~ 이렇게 있어야 443 뜸 
            System.out.println(u.getHost()); //도메인명
            System.out.println(u.getFile()); //실행파일(경로 + 파라미터값)
            System.out.println(u.getPath()); //현재파일 경로 
            System.out.println(u.getQuery()); //파라미터값

            InputStream is = u.openStream();
            InputStreamReader isr = new InputStreamReader(is,"utf-8");
            BufferedReader br = new BufferedReader(isr); //변환 완료

            FileOutputStream fs = new FileOutputStream("D:\\shop.html");
            PrintWriter pw = new PrintWriter(fs);

            String source = "";
            while((source = br.readLine()) != null) {
                pw.println(source);
                pw.flush(); //써도 되고 안써도 됨
            }

            pw.close();
            fs.close();
            br.close();
            isr.close();
            is.close();
        }catch(Exception e) {
            e.getMessage();
        }

}

 

🌸 server - client 메세지 주고받기( socket을 이용한 타server에 메세지,파일 전송 )

⚡ Server Open(Socket 통신 환경 - TCP)
내 소켓 오픈 -> 누군가 내 서버에 접속햇을시 파트

getInputStream : 클라이언트에서 적용된 메세지를 받는 역할
public class net5 {
	
	static Socket sk = null;
	
	public static void main(String[] args) {
		System.out.println("Server Connect!!");
		int port = 9000; //내서버 port 적용
		
		try {
			Scanner sc = new Scanner(System.in);
			ServerSocket ss = new ServerSocket(port); //해당 port를 open
			System.out.println("호스트 통신 연결 성공~"); //누가 한명 접속해야 뜸
			
			while(true) { //여러사람 접속 가능 , 계속 작동
				sk = ss.accept();
				
				
				//전송받기
				InputStream is = sk.getInputStream(); //전송 받음(읽음)
                
                //InputStream 얘가 문자의 크기를 못알아내서 안됨 , file일때는 available 가능
				//byte msg[] = new byte[is.available()];
                
				//최대 받을 수 있는 메세지양 설정(너무 작으면 글자 짤림)
				byte msg[] = new byte[2048]; 
				is.read(msg); //메세지 내용을 읽어들임 !!여기서 용량 확인!! 
				String result = new String(msg); //byte->String 변환
				
				//전송받은 메세지 출력
				System.out.println(result);
				
				//서버에서 전송
				String cms = sc.nextLine();
				OutputStream os = sk.getOutputStream();
				byte call[] = cms.getBytes();
				os.write(call);
				os.flush();
				
				os.close();
				is.close();
			}	
			
		}catch(Exception e) {
			System.out.println("현재 서버 포트 충돌로 인하여 서버를 가동하지 못합니당");
		}
	}
}


누군가 내 서버에 접속 , 내가 누군가 서버에 접속

⚡ Socket 통신 [ client 파트 ]
내가 남의 서버에 접속하는 파트

getOutputStream : 클라이언트 -> 서버로 전송하는 역할

public class net6 {

	//static:메모리에 저장(지금 main이라 붙은거임)/메세지 계속 주고받게 하기 위해 field로 뺌
	static Socket sk = null;  
	
	public static void main(String[] args) {
		int port=9000; //접속할 서버 port번호
		String ip="172.30.1.28"; //접속할 서버 ip주소
		
		System.out.println("클라이언트 접속 시도.....");
		Scanner sc = new Scanner(System.in);
		
		try {
			while(true) {
				sk = new Socket(ip,port);
				System.out.println("보낼 내용을 입력하세요 : ");
	
				//전송은 전부 byte로 이루어짐
				String msg = sc.nextLine();//사용자가 입력한 값 / byte로 변환 필요 
				
				//전송하기
				OutputStream os = sk.getOutputStream(); 
				byte m[] = msg.getBytes(); //문자를 byte로 변환
				os.write(m); //전송
				
				//서버에서 보낸 내용 클라이언트에서 출력
				InputStream is = sk.getInputStream(); //받기
				byte call[] = new byte[1024];
				is.read(call);
				String result = new String(call); //byte->String 변환
				
				System.out.println(result);
				
				is.close();
				os.flush(); //초기화			
				os.close();

			}
		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("서버에 접속하지 못하였습니다");
		}

	}

}

 

🌸 client -> server 이미지파일 전송하기

⚡ file 전송 [server] - FTP Server
이미지가 끊겨서 도착할 경우 반복문에 넣어서 끊어서 받아야 함
public class file_server {
	public static void main(String[] args) {
		new ftp_server(10000); //포트번호 넘기기
	}
}

class ftp_server{
	int p = 0; 
	Socket sk = null;
	ServerSocket ss = null;
	InputStream is = null;
	FileOutputStream fs = null; //파일을 저장할꺼니깐
			
	public ftp_server(int port) {
		this.p = port;
		this.data();
	}
	
	private void data() {
		try {
			this.ss = new ServerSocket(this.p); //포트번호 입력
			this.sk = this.ss.accept();
			System.out.println("*-*-*- 서버 가동중 -*-*-*");
			String url = "D:\\ftp\\"; //클라이언트가 전송한 파일 저장소
			
			//--클라이언트가 전송한 파일을 읽어들여서 체크함
			this.is = this.sk.getInputStream(); //날라올 파일 : byte 단위
			//용량 얼마까지 받을건지 byte로 변환하여 작성 (2MB 작성함)
			byte data[] = new byte[2097152];
			//this.is.read(data);
			
			//--서버에 저장하는 코드
			this.fs = new FileOutputStream(url + "data7.jpg");
			int filesize = 0;
			while((filesize = this.is.read(data)) != -1) { //끊어서 받기
				this.fs.write(data,0,filesize); //메모리가 부족할경우				
				this.fs.flush();
			}
			System.out.println("정상적으로 업로드 완료되었습니다^___^");
			
			this.fs.close();
			this.is.close();
			this.sk.close(); //socket 강제 종료
			
		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("port 충돌로 인하여 서버 오류 발생!!!");
		}
	}
	
}




client - ftp server에 file 전송

public class file_client {
	public static void main(String[] args) {
		new ftp_client("172.30.1.5",10000);
	}
}

class ftp_client {
	String ip= null;
	int port = 0;
	Socket sk = null;
	InputStream is = null;
	OutputStream os = null;
	
	public ftp_client(String serverip, int serverport) {
		this.ip = serverip;
		this.port = serverport;
		this.files();
	}
	
	private void files() {
		Scanner sc = new Scanner(System.in);
		
		try {
			this.sk = new Socket(this.ip,this.port);
			System.out.println("업로드할 이미지 경로를 입력하세용 : ");
			String url = sc.nextLine();
			
			//자신의 pc에 있는 파일을 메모리에 임시저장시킴
			this.is = new FileInputStream(url);
			BufferedInputStream bs = new BufferedInputStream(is); //빠르게
			byte img[] = new byte[bs.available()]; //available : 자기거
			bs.read(img);
			
			//서버로 전송
			this.os = this.sk.getOutputStream();
			this.os.write(img);
			
			this.os.flush();
			this.os.close();
			this.is.close();
			sc.close();
			System.out.println("파일 전송이 완료되었습니다 ^__^");
			
		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("서버에 접속하지 못하셨습니다ㅠ___ㅠ");
		}
	}
}

 

'CLASS > JAVA' 카테고리의 다른 글

#18-1 / 서버 - UDP  (0) 2024.05.27
#17 / remind3  (0) 2024.05.24
#16-1 / network 🔥  (0) 2024.05.23
#15-3 / csv 데이터 저장  (0) 2024.05.22
#15-2 / StreamWriter,StreamReader  (0) 2024.05.22