패키지 com.mepu,
가져 오기 org.junit.Test,
가져 오기 는 java.io * ;
가져 오기 java.net. * ;
/ **
* @author : ACON
* @date : 2020년 1월 1일 16시 1분
* @description 다음 TODO
* @modifiedBy는 :
* @version 1.0
* /
공용 클래스 IntelTest {
// 인스턴스화
@Test
공개 공극 TEST1 () 가 발생 UnknownHostException의 {
// 도메인 이름 호스트 구하는 대상
의 InetAddress 요소 별명 = InetAddress.getByName ( "www.baidu한다. COM " );
ByName1의 InetAddress ;InetAddress.getByName = ( "192.168.0.1" )
의 InetAddress byName2 = InetAddress.getByName ( "127.0.0.1" )
의 InetAddress 로컬 호스트 = InetAddress.getByName ( "로컬 호스트" );
// 일반적인 방법
// 도메인 이름 얻기
문자열 여기서 hostName = 요소 별명 .getHostName ();
// 호스트 주소 얻을
문자열 HOSTADDRESS = byName.getHostAddress ();
}
/ **
* 서버 시뮬레이트
* /
@Test
공공 무효 서버 () {
ServerSocket가 ServerSocket를 = null의
소켓이 적용 =널 (null) ;
InputStream 인 스트림 = 널 (null) ;
있는 ByteArrayOutputStream OutputStream에 = 널 ;
은 try {
// 빌드 포트 번호
ServerSocket를 = 새로운 새로운 ServerSocket가 (8899 );
// 소켓이 작성
수락 = serverSocket.accept ();
// 얻을 입력 스트림 객체
스트림 = accept.getInputStream ();
// 있는 ByteArrayOutputStream 중국어 문제가 해결 해결
바이트 [] B = 새로운 새 바이트 [1,024 ];
OutputStream에가 outputStream.close ();= 새 를 ByteArrayOutputStream ();
int로 렌;
반면 ((LEN = stream.read (b)) = -1! ) {
// 数据存入있는 ByteArrayOutputStream
outputStream.write (b, 0 , 렌);
}
// 输出
에서 System.out.println (outputStream.toString ());
} 캐치 (IOException이 전자) {
e.printStackTrace ();
} 마지막으로 {
시도 {
// 关闭流
stream.close ();
accept.close ();
serverSocket.close ();
} 캐치 (IOException가 E) {
e.printStackTrace ();
}
}
}
// 클라이언트
@Test
공공 무효 클라이언트 () {
소켓 소켓 = 널 (null) ;
OutputStream에 OutputStream에 = 널 ;
은 try은 {
// 도메인 설정
의 InetAddress 요소 별명 = InetAddress.getByName ( "127.0.0.1" )
// 소켓 만들기
소켓을 =을 새로운 새로운 소켓 (요소 별명, 8899 );
// 출력 스트림을 취득
OutputStream에 = ; Socket.getOutputStream ()
OutputStream.write ( "! I 클라이언트 안녕하세요" ); .getBytes ()
} 캐치 (IOException가 E) {
e.printStackTrace ();
} 최종적으로 {
은 try {
// 가까운 흐름
outputStream.close ();
Socket.close ();
} 캐치 (IOException가 E) {
e.printStackTrace ();
}
}
}
}
연결을 생성하고 서버와 클라이언트를 시뮬레이션
추천
출처www.cnblogs.com/aikang525/p/12129343.html
추천
행