웹프로그래밍/Java
자바 소켓통신
marmelo12
2023. 10. 8. 23:44
반응형
외부 통신을 위한 소켓 프로그래밍 작성
서버 코드
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class main {
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
Socket s = new Socket("대충 도메인 주소",9999);
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
int cnt = 0;
while(true) {
if(cnt >= 100)
break;
os.write(("serverTest " + cnt).getBytes());
os.flush();
byte[] readData = new byte[100];
int len = is.read(readData);
System.out.println(new String(readData,0,len));
Thread.currentThread().sleep(5000);
++cnt;
}
s.close();
}
}
클라 코드
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket socket = new ServerSocket(9999);
// 연결된 소켓을 반환.
Socket s = socket.accept();
// 해당 소켓(클라이언트)의 입출력 스트림 가져오기
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
try {
while(true) {
byte[] readData = new byte[100];
int len = is.read(readData);
os.write(new String(readData,0,len).getBytes());
os.flush();
}
}catch(Exception e) {
return;
}
}
}
내부망에선 연결확인했고, 외부에서 연결시도해볼 예정.
- http://check.psinno.co.kr/index.html 여기서 외부에서 접속 테스트 확인해볼 수 있음.
위 과정까지 한 것들.
- DDNS설정(no-ip 무료 도메인 30일짜리, 동적ip 주기적으로 업데이트)
- 현재 PC가 모뎀으로부터 랜선이 바로 꼽혀있기에 따로 포트포워딩은 X
참고
반응형