import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
/*
* 需求:发送数据后,接收服务器的反馈
*/
public class ClientDemo {
public static void main(String[] args) throws IOException {
// 创建客户端对象
Socket s = new Socket(InetAddress.getByName("192.168.1.100"), 12345);
// 获取输出流
OutputStream os = s.getOutputStream();
os.write("hello,给你发点数据".getBytes());
// 接收服务器反馈
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);
String server = new String(bys, 0, len);
System.out.println("server:" + server);
// 释放资源
s.close();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*
* 需求:接收客户端的数据,并给一个反馈
*/
public class ServerDemo2 {
public static void main(String[] args) throws IOException {
// 创建服务器Socket对象
ServerSocket ss = new ServerSocket(12345);
// 监听并获取当前客户端对象
Socket s = ss.accept();
// 获取输入流
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);
String client = new String(bys, 0, len);
System.out.println("client:" + client);
// 获取输出流
OutputStream os = s.getOutputStream();
os.write("数据已收到".getBytes());
// 释放资源
s.close();
ss.close();
}
}
此方法ss.accept(),API中说是有阻塞状态,请问它具体是怎么阻塞的?是不是程序走到这里的时候,程序暂停,等客户端输入好了流对象后,才执行下面的代码?;
|
|