发送端
public class ClientDemo {
public static void main(String[] args) throws IOException {
// 创建客户端的Socket对象(Socket)
Socket s=new Socket("192.168.40.1",1245);
// 获取输出流,写数据
OutputStream os = s.getOutputStream();
os.write("hello,tcp,我来了".getBytes());
// 释放资源
s.close();
}
}
接收端
public class ServerDemo {
public static void main(String[] args) throws IOException {
//1.创建服务器的Socket对象(ServerSocket)
ServerSocket ss = new ServerSocket(1245);
//2.获取输入流,读数据,并把数据显示在控制台
Socket s = ss.accept();
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);
String data = new String(bys, 0, len);
System.out.println("数据是:" + data);
//3.释放资源
s.close();
ss.close();
}
}