package com.beicai.net; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * Created by lenovo on 2017/10/19. */ public class TestTCP2 { //ipconfig //客户端 @Test public void client() { Socket socket = null; OutputStream outputStream = null; InputStream inputStream = null; try { socket = new Socket("10.114.19.226",9090); outputStream = socket.getOutputStream(); outputStream.write("瞅你咋地".getBytes()); socket.shutdownOutput();// inputStream = socket.getInputStream(); byte[] bytes = new byte[20]; int len; while ((len = inputStream.read(bytes))!=-1){ String string = new String(bytes,0,len); System.out.println(string); } // outputStream = socket.getOutputStream(); // outputStream.write("试试就试试".getBytes()); // socket.shutdownOutput(); } catch (IOException e) { e.printStackTrace(); }finally { if (inputStream!=null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null){ try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } //服务端 @Test public void server(){ ServerSocket serverSocket = null; Socket socket = null; InputStream inputStream = null; OutputStream outputStream = null; try { serverSocket = new ServerSocket(9090); socket = serverSocket.accept(); inputStream = socket.getInputStream(); byte[] bytes = new byte[20]; int len; while ((len = inputStream.read(bytes))!= -1){ String string = new String(bytes,0,len); System.out.println(string); } outputStream = socket.getOutputStream(); outputStream.write("在瞅一个试试".getBytes()); inputStream = socket.getInputStream(); // socket.shutdownOutput();// // outputStream.write("。。。".getBytes()); } catch (IOException e) { e.printStackTrace(); }finally { if (outputStream!=null){ try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (serverSocket != null){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if (inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
TCP编程例一:客户端给服务端发送信息,服务端给客户端发消息
最新推荐文章于 2023-09-06 19:00:29 发布