import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
final static int SERVER_PORT = 1225;
final static String MESSAGE_TO_SERVER = "Hello world!!! receive message from Client";
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(SERVER_PORT);
} catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
Socket socket = serverSocket.accept();
/** Server에서 보낸 값을 받기 위한 통로 */
InputStream is = socket.getInputStream();
/** Server에서 Client로 보내기 위한 통로 */
OutputStream os = socket.getOutputStream();
byte[] data = new byte[16];
int n = is.read(data);
final String messageFromClient = new String(data,0,n);
System.out.println(messageFromClient);
os.write( MESSAGE_TO_SERVER.getBytes() );
os.flush();
is.close();
os.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SocketRun implements Runnable {
private Socket socket = null;
SocketRun( Socket socket ){
this.socket = socket;
}
@Override
public void run() {
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private static final String SERVER_IP = "127.0.0.1";
private static int SERVER_PORT = 1225;
private static final String MESSAGE_TO_SERVER = "Hellow world!!! send message to Server";
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
System.out.println("socket 연결");
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
os.write(MESSAGE_TO_SERVER.getBytes());
os.flush();
byte[] bytes = new byte[16];
int n = is.read(bytes);
final String resultFromServer = new String(bytes,0,n);
System.out.println(resultFromServer);
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}
댓글 영역