갑자기 채팅 프로그램을 짜보고 싶어서, 유투브 보면서 소스 따라하기가 의외로 재미 있어서 놀람.
Server
package chat1;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
private ServerSocket serverSocket;
private Socket clientSocket;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
public void serverSetting(){
try {
System.out.println("서버 start...");
// localhost 10002 포트
serverSocket = new ServerSocket(10002);
clientSocket = serverSocket.accept();
// 소켓의 접속완료
System.out.println("클라이언트 소켓 연결");
} catch (Exception e) {
e.printStackTrace();
}
}
public void closeAll(){
try {
serverSocket.close();
clientSocket.close();
dataInputStream.close();
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void streamSetting(){
try {
dataInputStream = new DataInputStream(clientSocket.getInputStream());
dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
public String dataRecv(){
try {
return dataInputStream.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void dataSend(String sendData){
try {
dataOutputStream.writeUTF(sendData);
} catch (IOException e) {
e.printStackTrace();
}
}
public ServerTest(){
serverSetting();
streamSetting();
System.out.println(dataRecv());
dataSend("굿 잡 맨");
closeAll();
}
public static void main(String[] args){
new ServerTest();
}
}
Client
package chat1;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class ClientTest {
private Socket clientSocket;
private DataInputStream dataInputStream;
private DataOutputStream dataOutputStream;
public void connect(){
try {
clientSocket = new Socket("192.168.0.1", 10002);
System.out.println("접속 완료!");
} catch (Exception e) {
e.printStackTrace();
}
}
public void streamSetting(){
try {
dataInputStream = new DataInputStream(clientSocket.getInputStream());
dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
public String dataRecv(){
try {
return dataInputStream.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void dataSend(String sendData){
try {
dataOutputStream.writeUTF(sendData);
} catch (IOException e) {
e.printStackTrace();
}
}
public ClientTest() {
connect();
streamSetting();
dataSend("안녕 난 클라이언트야");
System.out.println(dataRecv());
}
public static void main(String[] args){
new ClientTest();
}
}
아래 유투브 강의를 참고했다.
https://www.youtube.com/watch?v=LEngL3wg-8k
이어서 채팅 프로그램을 구현한다.
'Java' 카테고리의 다른 글
해쉬 이해하기(Java) (0) | 2018.09.12 |
---|---|
Spring fileupload maven (0) | 2017.12.06 |
프로그래밍은 참 어렵다. (0) | 2017.11.21 |
이클립스 웹프로젝트 톰캣 index.html이 404가 뜨다! (4) | 2017.03.16 |
apache commons exec 을 이용한 java에서 linux script 실행 (0) | 2017.01.18 |