[개발] - Java/Mega
Day32. 네트워크 (3) 예제
완벽한 장면
2023. 5. 6. 21:29
UDP
public class SendUDPEX {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DatagramSocket ds = new DatagramSocket();
InetAddress ia = InetAddress.getByName("192.168.20.34");
int port = 8888; //리시브 안 켜고서 send부터 켜면 안 된다.
Scanner sc = new Scanner(System.in);
System.out.print("입력 : ");
String str = sc.next();
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length, ia, port);
ds.send(dp);
}
}
public class ReceiveUDPEX {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int port = 8888;
int times = 10;
DatagramSocket ds = new DatagramSocket(port);
int i = 1;
while(i<= times) {
byte[] buffer = new byte[30];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String str = new String(dp.getData());
System.out.println("수신된 데이터 : " + str);
i++;
}
}
}
TCP
public class ServerTCPEX {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int port = 7777;
int times = 10;
ServerSocket ss = new ServerSocket(port);
int i = 1;
while(i<=times) {
Socket s = ss.accept(); // 여기서 멈춰있다가, 클라이언트 접속이 되면 아래로 들어간다.
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
for(int j = 1; j<10; j++) {
dos.write(j);
}
s.close();
i++;
}
ss.close();
}
}
public class ClientTCPEX {
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
String server ="192.168.20.34"; //cmd : ipconfig
int port = 7777;
// 서버를 켜고 클라이언트를 켜니까
// 얘가 접속을 하면 서로 연결된 소켓을 하나씩 받는다(s에서도 받고 c에서도 받고)
Socket c = new Socket(server, port);
InputStream is = c.getInputStream();
DataInputStream dis = new DataInputStream(is);
for(int i = 1; i<= 10; i++) {
int j = dis.read();
System.out.println("서버로부터 받은 데이터 " + j + "출력");
}
c.close();
}
}
728x90
반응형