티스토리 뷰

반응형


SERVER


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) {

}

}


}


}





댓글

티스토리 방명록

최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday