服务器端
@Testpublic void testServer() {
ServerSocket serverSocket = null;Socket accept = null;InputStream acceptInputStream = null;ByteArrayOutputStream byteArrayOutputStream = null;try {
serverSocket = new ServerSocket(8899);accept = serverSocket.accept();acceptInputStream = accept.getInputStream();byteArrayOutputStream = new ByteArrayOutputStream();byte[] bytes = new byte[1024];int len;while ((len = acceptInputStream.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, len);}} catch (IOException e) {
e.printStackTrace();} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();} catch (IOException e) {
e.printStackTrace();}}if (acceptInputStream != null) {
try {
acceptInputStream.close();} catch (IOException e) {
e.printStackTrace();}}}System.out.println(byteArrayOutputStream.toString());System.out.println(accept.getInetAddress());}
客户端
@Testpublic void testClient() {
Socket socket = null;OutputStream socketOutputStream = null;try {
socket = new Socket(InetAddress.getByName("10.212.10.194"), 8899);socketOutputStream = socket.getOutputStream();socketOutputStream.write("我是爸爸".getBytes());} catch (IOException e) {
e.printStackTrace();} finally {
if (socketOutputStream != null) {
try {
socketOutputStream.close();} catch (IOException e) {
e.printStackTrace();}}}}