java 복습 - 서버 및 클라이언트 socke
2833 단어 java 복습
import org.junit.Test;
import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket;
/**
*/public class TCPJava {
@Test
//
public void client(){
OutputStream os = null;
Socket socket = null;
try {
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 9988);
os = socket.getOutputStream();
os.write(" , GG!".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
//
public void server() throws IOException {
/**
* * 1、 ServerSocket,
* * 2、 accept() socket
* * 3、
* * 4、
* * 5、
*/
ServerSocket serverSocket = null;
Socket accept = null;
InputStreamReader isr = null;
ByteArrayOutputStream bis =null;
try {
//1、 ServerSocket,
serverSocket = new ServerSocket(9988);
//2、serverSoceket accept
accept = serverSocket.accept();
//3、
InputStream os = accept.getInputStream();
//방식1://isr = new InputStreamReader(os);///흐르는 데이터 읽기//char[] buffer = new char[5];///int len;//StringBuffer strB = new StringBuffer();//while ((len = isr.read(buffer)) != -1){ //strB.append(buffer,0,len);//}//System.out.println(strB);
// :
bis = new ByteArrayOutputStream();
byte[] buffer = new byte[5];
int len;
while ((len = os.read(buffer)) != -1){
bis.write(buffer,0,len);
}
System.out.println(bis.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
//4、
//if (isr != null){ //isr.close();//}//if (accept != null){ //accept.close();//}//if (serverSocket != null){ //serverSocket.close();//} if (bis != null){ bis.close();
}
if (isr != null){
isr.close();
}
if(accept != null){
accept.close();
}
if( serverSocket != null){
serverSocket.close();
}
}
}
}