- import java.io.*;
- import java.net.*;
- class TcpClient
- {
- public static void main(String[] args) throws Exception
- {
- //创建客户端的Socket服务,指定目的主机和端口。
- Socket s = new Socket("192.168.1.106",10003);
- //为了发送数据,应获取Socket服务里的输出流
- OutputStream out = s.getOutputStream();
- out.write("给你发点数据".getBytes());
- s.close();
- }
- }
- class TcpServer
- {
- public static void main(String[] args) throws Exception
- {
- //1.建立服务端的socket服务。并监听一个端口
- ServerSocket ss = new ServerSocket(10003);
- //2.通过accept()方法获取连接过来的客户端对象
- Socket s = ss.accept();
- String ip = s.getInetAddress().getHostAddress();
- System.out.println(ip+"||||");
- //3.获取到该客户端对象的读取流来读取发过来的数据
- InputStream in = s.getInputStream();
- byte[] buf = new byte[1024];
- int len = in.read(buf);
- System.out.println(new String(buf,0,len));
- }
- }
- /*
- H:\testjava>javac TcpDemo.java
- H:\testjava>java TcpServer
- 192.168.1.106||||
- 给你发点数据
- H:\testjava>
- */
复制代码
|