client客户端
new Thread(new Runnable() {
@Override
public void run() {
try {
//初始化接口对象
s = new Socket("127.0.0.1", shellport);
//实例化输出流对象
os = s.getOutputStream();
//通过流传输数据
os.write("hello".getBytes());
//关闭流
s.shutdownOutput();
//关闭接口对象
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
Server服务端
new Thread(new Runnable() {
@Override
public void run() {
//保持服务端一直存在
while (true) {
try {
//初始化一个套接字接口对象,ip:0.0.0.0,端口随机
ss = new ServerSocket(0);
} catch (IOException e) {
e.printStackTrace();
}
//获取端口号,给客户端用
shellport = ss.getLocalPort();
try {
//开启监听状态,开始阻塞,直到有客户端socket连接过来,才开始通行
socket = ss.accept();
} catch (IOException e) {
e.printStackTrace();
}
try {
char[] cs = new char[10];
socket.setSoTimeout(10000);
//从输入流中读取来自客户端的数据
new BufferedReader(new InputStreamReader(socket.getInputStream())).read(cs);
//关闭输入流
socket.shutdownInput();
Log.e("接收数据", String.valueOf(cs));
//关闭套接字
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
网友评论