클라이언트가 서버에 연결하여 메세지를 보내면 서버에 메세지를 띄워주고
서버에서 메세지를 보내면 클라이언트에 메세지를 띄워준다.
server.java
import java.io.*;
import java.net.*;
public class UniServer {
private ServerSocket serverS;
Socket tcpSocket = null;
public UniServer(int port) {
try{
serverS = new ServerSocket(port); //서버 소켓 생성
System.out.println("클라이언트의 요청을 기다리는 중");
while(true) { //무한반복으로 클라이언트 요청 받아주기
tcpSocket = serverS.accept(); //클라이언트 연결시 클라이언트와 연동할 소켓 생성
System.out.println("사용자 접속 : " + tcpSocket.getInetAddress());
UniSend send = new UniSend(tcpSocket); //메세지 보내는 클래스 객체 생성
Unireceive receive = new Unireceive(tcpSocket); //메세지 받는 클래스 객체 생성
send.start(); // 보내는 스레드 시작
receive.start(); // 받는 스레드 시작
}
}catch(IOException ioe){
ioe.printStackTrace();
System.exit(0);
}
}
public static void main(String[] args){
new UniServer(3000); //서버 객체 생성
}
}
client.java
import java.io.IOException;
import java.net.*;
public class UniClient {
private String ip;
private int port;
Socket tcpSocket = null;
public UniClient(String ip, int port) throws UnknownHostException, IOException {
this.ip = ip; //통신할 서버의 아이피
this.port = port; // 서버와 통신할 포트번호
tcpSocket = new Socket(ip, port); // 소켓 생성
System.out.println("서버 접속!");
UniSend send = new UniSend(tcpSocket);
Unireceive receive = new Unireceive(tcpSocket);
send.start();
receive.start();
}
public static void main(String[] args) throws IOException {
new UniClient("localhost", 3000); //클라이언트 객체 생성
}
}
send.java
import java.io.*;
import java.net.Socket;
public class UniSend extends Thread{
private String str;
Socket tcpSocket = null;
public UniSend(Socket tcpSocket) {
this.tcpSocket = tcpSocket; //소켓 저장
}
public void run() {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(tcpSocket.getOutputStream());
while(true) { //무한 반복으로 메세지 입력 받기
str = reader.readLine();
if (str.equals("bye")) { //bye 입력시 종료
break;
}
writer.println(str); //자동 개행
writer.flush(); //메세지 보내기
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
tcpSocket.close();
} catch (Exception ignored) {
}
}
}
}
recive.java
import java.io.*;
import java.net.*;
public class Unireceive extends Thread{
private BufferedReader bufferR;
private BufferedWriter bufferW;
Socket tcpSocket = null;
public Unireceive(Socket tcpSocket) {
this.tcpSocket = tcpSocket; //소켓 저장
}
public void run() {
String message;
try {
bufferR = new BufferedReader( new InputStreamReader(tcpSocket.getInputStream()));
while(true) {
message = bufferR.readLine(); //읽기
if(message == null) { //소켓 종료로 null값이 오는경우
System.out.println("수신메시지 : bye");
break;
}
System.out.println("수신메시지 : "+ message); //출력
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
'자바' 카테고리의 다른 글
Get 과 Post 방식 (0) | 2022.09.04 |
---|---|
OSI 7계층 (0) | 2022.09.04 |
리뷰 남기기 (0) | 2022.09.01 |
네이버 뉴스 크롤링 (0) | 2022.09.01 |
마이페이지 기능 (0) | 2022.09.01 |