package com.beicai.Demo19; import com.sun.security.ntlm.Server; 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 user on 2017/10/19. */ //TPC编程例一,客户端给服务端发送信息。服务器端出此信息到控制台 public class TestTCP { //客户端 @Test public void client() { Socket socket = null; OutputStream outputStream = null; try { socket = new Socket("10.114.19.1", 9090); outputStream = socket.getOutputStream(); outputStream.write("你瞅啥?".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { 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 ss = null; Socket s = null; InputStream is = null; try { ss = new ServerSocket(9090); s = ss.accept(); is = s.getInputStream(); byte[] b= new byte[20]; int len; while ((len = is.read(b))!=-1){ String str = new String(b,0,len); System.out.println(str); } } catch (IOException e) { e.printStackTrace(); }finally { if (is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (s != null){ try { s.close(); } catch (IOException e) { e.printStackTrace(); } } if ( ss != null){ try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
建立TCP
最新推荐文章于 2021-04-09 14:17:45 发布