TCP传送数据
-
创建客户端的Socket对象
Socket(String host,int port)
-
获取输出流OutPutStream
OutPutStream getOutPutStream()
-
写数据
getOutPutStream().write()
-
释放资源
close
public class SendDemo {
public static void main(String[] args) throws IOException {
Socket s=new Socket("192.168.101.1",12345);
OutputStream outputStream = s.getOutputStream();
outputStream.write("hello,world".getBytes());
outputStream.close();
}
}
TCP接收数据
-
创建服务器端ServerSocke对象
ServerSocket(int port)
-
监听客户端连接,返回一个Socket对象
Socket accpet()
-
获取输入流InputStream
InputStream getInputStream()
-
释放资源
close
public class ReceiveDemo {
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(12345);
Socket socket = s.accept();
InputStream inputStream = socket.getInputStream();
byte[] b = new byte[1024];
int len = inputStream.read(b);
// while((len=inputStream.read())!=-1){
// String s1 = new String(b, 0, len);
// System.out.println("数据是"+s1);
// }
String s1 = new String(b, 0, len);
System.out.println("数据是" + s1);
socket.close();
inputStream.close();
}
} -