본문 바로가기
programming/JAVA

[JAVA] 소켓통신을 이용한 데이터 송수신

by kvve 2021. 9. 10.

배열 a와 배열 b의 전체 요솟값을 교환하는 aryExchng메소드를 작성하라.
void aryExchng(int [] a,int[] b){
}
두 배열의 요소 수가 같지 않으면 작은 쪽의 배열수에 맞추어 교환할것

import java.util.Scanner;

public class main {
	
	static void aryExchng(int [] a,int[] b){
		int n = a.length < b.length ? a.length : b.length;
		for(int i = 0; i<n; i++) {
			int t = a[i];
			a[i] = b[i];
			b[i] = t;
		}
		
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("배열 a의 요소 수 : ");
		int na = sc.nextInt();	//배열 a의 요소 수
		int[]a = new int[na];	//요소 수가 na인 배열
		for(int i = 0; i< na; i++) {
			System.out.print("a[" + i + "]:");
			a[i] = sc.nextInt();
		}
		
		System.out.println("배열 b의 요소 수 : ");
		int nb = sc.nextInt();	// 배열 b의 요소 수
		int[] b = new int[nb];
		for(int i = 0; i< nb; i++) {
			System.out.print("b[" + i + "]:");
			b[i] = sc.nextInt();
		}
		
		aryExchng(a,b);
		System.out.println("배열 a,b 요소 교환완료");
		for(int i = 0; i<na; i++) {
			System.out.println("a[" + i + "]= " + a[i]);
		}
		System.out.println();
		for(int i = 0; i<nb; i++) {
			System.out.println("b[" + i + "]= " + b[i]);
		}
	}
}

2. 소켓통신

//서버
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerExample {
   public static void main(String[] args) {
      ServerSocket serverSocket = null;
      try {
         serverSocket = new ServerSocket();
         serverSocket.bind(new InetSocketAddress("localhost", 5001));
         while (true) {
            System.out.println("[연결 기다림]");
            Socket socket = serverSocket.accept();
            InetSocketAddress isa = (InetSocketAddress) socket.getRemoteSocketAddress();
            System.out.println("[연결 수락함]" + isa.getHostName());
         }
      } catch (Exception e) {
      }

      if (!serverSocket.isClosed()) {
         try {
            serverSocket.close();
         } catch (IOException e1) {
         }
      }
   }
}
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ClientExample {

   public static void main(String[] args) {
      Socket socket = null;
      try {
         socket = new Socket();
         System.out.println("[연결 요청]");
         socket.connect(new InetSocketAddress("localhost",5001) );
         System.out.println("[연결 성공]");
      }catch(Exception e) {}
      if(!socket.isClosed()) {
         try {
            socket.close();
         }catch (IOException e1) {}
      }
   }

}

3. 소켓통신(텍스트 전송 프로그램)

//server
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SeverExample {

   public static void main(String[] args) {
      ServerSocket serverSocket = null;
      try {
         serverSocket = new ServerSocket();
         serverSocket.bind(new InetSocketAddress("localhost",5002));
         while(true) {
            System.out.println("[연결 기다림]");
            Socket socket = serverSocket.accept();
            InetSocketAddress isa =(InetSocketAddress) socket.getRemoteSocketAddress();
            System.out.println("[연결 수락함]"+ isa.getHostName());
            
            byte[] bytes =null;
            String message =null;
            
            InputStream is = socket.getInputStream();
            bytes =new byte[100];
            int readByteCount =is.read(bytes);
            message =new String(bytes, 0,readByteCount, "UTF-8");
            System.out.println("[데이터 받기 성공]:"+ message);
            
            OutputStream os =socket.getOutputStream();
            message = "Hello Client";
            bytes =message.getBytes("UTF-8");
            os.write(bytes);
            os.flush();
            System.out.println("[데이터 보내기 성공]");
            
            is.close();
            os.close();
            socket.close();

         
         }
      }catch(Exception e) {}
      if(!serverSocket.isClosed()) {
         try {
            serverSocket.close();
         }catch (IOException e1) {}
      }

   }

}
//Client

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ClientExample {

	public static void main(String[] args) {
		Socket socket = null;
		try {
			socket = new Socket();
			System.out.println("[연결 요청]");
			socket.connect(new InetSocketAddress("localhost", 5002));
			System.out.println("[연결 성공]");

			byte[] bytes = null;
			String message = null;

			OutputStream os = socket.getOutputStream();
			message = "Hello my name MyungJin";
			bytes = message.getBytes("UTF-8");
			os.write(bytes);
			os.flush();
			System.out.println("[데이터 보내기 성공]");

			InputStream is = socket.getInputStream();
			bytes = new byte[100];
			int readByteCount = is.read(bytes);
			message = new String(bytes, 0, readByteCount, "UTF-8");
			System.out.println("[데이터 받기 성공] : " + message);

			os.close();
			is.close();
		} catch (Exception e) {
		}

		if (!socket.isClosed()) {
			try {
				socket.close();
			} catch (IOException e1) {
			}
		}
	}

}

 

[출처] 이것이 자바다(한빛 미디어)

댓글