标签:
Java中Socket的使用
client端
package org.tizen.test; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.SocketTimeoutException; public class TestSocket { public static void main(String []str) { OutputStream os = null; Socket socket = null; try { //1.创建socket的对象,通过构造器指明服务端的IP地址,以及接收的端口号 socket = new Socket(InetAddress.getByName("192.168.1.104"),9000); //2.getOutputStream发送数据,返回OutputStream os = socket.getOutputStream(); //3.具体的输出过程 os.write("1111111111 1111111111".getBytes()); } catch (Exception e) { // TODO: handle exception }finally { //4.关闭具体的流和socket if(os!=null) { try { os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(socket!=null) { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
server端
package org.tizen.test; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class TestTCPIP { public static void main(String []str) { ServerSocket ss = null; Socket s = null; InputStream is = null; try { //1. 创建一个SocketServer的对象,通过构造器指明自己的端口 ss = new ServerSocket(9000); //2.调用SocketServer的accept方法,返回一个Socket对象 s = ss.accept(); //3.调用Socket对象的getInputStream获得客户端发送过来的流 is = s.getInputStream(); byte[] b = new byte[20]; int len; while((len = is.read(b))!=-1) { String str1 = new String(b,0,len); System.out.println(str1); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u014338577/article/details/46953189