客户端A与服务端建立通信,服务端获取到客户端A的Socket对象,通过这个通路进行通信
客户端:
获取Socket对象,new出来,创建客户端的Socket服务,构造参数:Sting主机,int 端口
调用Socket对象的getOutputStream()方法,获取输出流OutputStream对象
调用OutputStream对象的write()方法,参数:byte[]字节数组
import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; /** * 客户端 * @author taoshihan * */ public class Client { public static void main(String[] args) throws Exception, IOException { Socket socket=new Socket(InetAddress.getLocalHost(), 10003); OutputStream outputStream=socket.getOutputStream(); outputStream.write("Hello TCP".getBytes()); } }
服务端:
获取ServerSocket对象,new出来,构造参数:int端口
调用ServerSocket对象的accept()方法,获取到Socket对象,阻塞式的
调用Socket对象的getInputStream()方法,获取输入流InputStream对象
读取输入流,数据量不大,不循环了直接调用InputStream对象的read()方法,参数:byte[]数组
调用Socket对象的getInetAddress()方法,获取到InetAddress对象
调用Socket对象的close()方法,关闭客户端
import java.io.InputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; /** * 服务端 * * @author taoshihan * */ public class Server { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(10003); while (true) { Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); byte[] buf = new byte[1024]; int len = inputStream.read(buf); InetAddress ip = socket.getInetAddress(); socket.close(); System.out.println("来自" + ip.getHostAddress() + "说:" + new String(buf, 0, len)); } } }
时间: 2024-11-03 19:15:54