发送数据
java
public class sendmessage {
public static void main (String[] args) throws IOException {
//创建socket对象
//在创建的同时会连接服务器,若连接不上,代码会报错
Socket socket=new Socket("127.0.0.1",10086);
//从连接通道中获取输出流
OutputStream os=socket.getOutputStream();
//写出数据
os.write("aaa".getBytes());
//释放数据
os.close();
socket.close();
}
}
接收数据
java
public class receivemessage {
public static void main (String[] args) throws IOException {
//创建ServerSocket对象
ServerSocket ss=new ServerSocket(10086);
//监听客户端的连接
Socket socket=ss.accept();
//从连接通道中获取输入流读取数据
//若想获取中文, 可将下句改为
//InputStreamReader isr=new InputStreamReader(socket.getInputStream());
InputStream is=socket.getInputStream();
int b;
while ((b=is.read())!=-1){
System.out.print((char) b);
}
//释放资源
socket.close();
ss.close();
}
}
要先运行接收端再运行发送端,否则无法收到数据
初学者,见解不足,如有错误请指出