标签:
import java.net.*; import java.io.*; class TcpClient { public static void main(String[] args)throws Exception { //创建客户端的Socket服务,指定目的主机和端口 Socket s = new Socket("192.168.1.105",8888); //为了发送数据,应该获取Socket中的输出流, OutputStream out = s.getOutputStream(); out.write("tcp is coming!".getBytes()); //关闭客户端流 s.close(); } }
class TcpServer { public static void main(String[] args)throws Exception { //建立服务端的Socket服务,并监听一个端口 ServerSocket ss = new ServerSocket(8888); //通过accept方法获取连接过来的客服端对象 Socket s = ss.accept(); String IP = s.getInetAddress().getHostAddress(); System.out.println(IP+"...connected!"); //获取客户端发送给来的数据,服务端要使用客服端对象的读取流类读取数据。方法InputStream getInputStream() InputStream in = s.getInputStream(); byte[] buf = new byte[1024]; int len = in.read(buf); System.out.println(new String(buf,0,len)); s.close();//关闭客户端 ss.close();//关闭服务端(可选操作) } }
标签:
原文地址:http://www.cnblogs.com/XYQ-208910/p/4918895.html