代码1
//客户端 import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; public class Client { public static void main(String[] args) throws IOException { //创建客户端socket Socket socket=new Socket("localhost",8888); //获取输出流对象 OutputStream os = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); //写出数据 dos.writeUTF("你好啊,弟弟"); //关闭客户端socket,关闭流 dos.close(); socket.close(); } } //服务端 import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws IOException { //创建socket服务端对象 ServerSocket serverSocket=new ServerSocket(8888); //获取来连接的客户端socket对象 Socket socket=serverSocket.accept(); //获取输入流对象 InputStream inputStream=socket.getInputStream(); DataInputStream dis=new DataInputStream(inputStream); //取出数据 String s = dis.readUTF(); System.out.println("收到消息:\t"+s); //关闭资源 dis.close(); serverSocket.close(); } }
代码2