티스토리 뷰
Java Client, Server data communication example 클라이언트, 서버 데이터통신 예제(이것이 자바다)
j0n9m1n1 2017. 11. 1. 17:22SERVER
package network;
import java.io.*;
import java.net.*;
public class ServerExample {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress("localhost", 7121));
while(true) {
System.out.println("WATING CONNECT");
Socket socket = serverSocket.accept();
InetSocketAddress isa = (InetSocketAddress) socket.getRemoteSocketAddress();
System.out.println("ACCEPT THE CONNECT(" + 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("SUCCESS THE RECEIVE DATA\n" + message);
OutputStream os = socket.getOutputStream();
message = "Hello Clinet";
bytes = message.getBytes("UTF-8");
os.write(bytes);
os.flush();
System.out.println("SUCCESS THE SEND DATA\n" + message);
}
}catch(Exception e) {
}
if(!serverSocket.isClosed()) {
try {
serverSocket.close();
}catch(IOException e1) {
}
}
}
}
CLIENT
package network;
import java.net.*;
import java.io.*;
public class ClientExample {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket();
System.out.println("REQUEST THE CONNECT");
socket.connect((new InetSocketAddress("localhost", 7121)));
System.out.println("SUCCESS THE CONNECT");
byte[] bytes = null;
String message = null;
OutputStream os = socket.getOutputStream();
message = "Hello Server";
bytes = message.getBytes("UTF-8");
os.write(bytes);;
os.flush();
System.out.println("SUCCESS SEND A MESSAGE\n");
InputStream is = socket.getInputStream();
bytes = new byte[100];
int readByteCount = is.read(bytes);
message = new String(bytes, 0, readByteCount, "UTF-8");
System.out.println("SUCCESS RECEIVE MESSAGE\n" + message);
os.close();
is.close();
}catch(Exception e) {
}
if(!socket.isClosed()) {
try {
socket.close();
}catch(IOException e1) {
}
}
}
}
'Java > for Class, Project' 카테고리의 다른 글
은행권 공동 플랫폼 API 사용에 대한 정보입니다. (6) | 2017.11.08 |
---|---|
PBL 프로젝트 문서 관련 요구 사항 (0) | 2017.11.06 |
Java client, server connect example 클라이언트, 서버 연결 예제 only connect (0) | 2017.11.01 |
Java TCP 네트워킹 (tcp networking) 노트 (이것이 자바다2) (0) | 2017.11.01 |
JAVA 자바 채팅 인터페이스, 로그인(Chat interface, login only, JFrame, WindowBuilder) (0) | 2017.10.28 |
티스토리 방명록
- Total
- Today
- Yesterday
Contact: j0n9m1n1@gmail.com