标签:style blog io color os sp java on div
package lianxi1; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import org.junit.Test; public class TestTCP1 { // 客户端 @Test public void client() { Socket s = null; InputStream is = null; OutputStream os = null; try { s = new Socket(InetAddress.getByName("127.0.0.1"), 9090); //s = new Socket(InetAddress.getByName("221.192.74.152"), 9090); //对方主机的IP地址 os = s.getOutputStream(); String str1 = "我是客户端,请接收"; os.write(str1.getBytes()); s.shutdownOutput(); 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.print(str); } } catch (Exception e) { // TODO: handle exception } finally{ if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (os != null) { try { os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (s != null) { try { s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } // 服务器 @Test public void server() { ServerSocket ss = null; Socket s = null; InputStream is = null; OutputStream os = 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.print(str); } os = s.getOutputStream(); os.write("已收到客户端信息".getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if (os != null) { try { os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (s != null) { try { s.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (ss != null) { try { ss.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
标签:style blog io color os sp java on div
原文地址:http://www.cnblogs.com/yjtm53/p/4167721.html