客户端
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class Client { public static void main(String[] args) throws IOException { // TODO 自动生成的方法存根 //创建一个socket对象,构造方法绑定服务器的IP地址和端口号 Socket socket=new Socket("127.0.0.1",8888); //获取输出流对象 OutputStream os=socket.getOutputStream(); //给服务器发送对象 os.write("你好服务器".getBytes()); //获得网络字节输入流对象 InputStream is =socket.getInputStream(); //读取服务器写回的数据 byte[] bytes= new byte [1024]; int len= is.read(bytes); System.out.println(new String(bytes,0,len)); //释放资源 socket.close(); }
服务端
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws IOException { // TODO 自动生成的方法存根 // 创建serversocket对象和系统要指定的端口号 ServerSocket server=new ServerSocket(8888); // 获得请求端对象 Socket socket=server.accept(); // 使用socket获得网络字节输入流对象 InputStream is=socket.getInputStream(); // 读取客户端发送的数据 byte[] bytes= new byte [1024]; int len= is.read(bytes); System.out.println(new String(bytes,0,len)); // 获得网络字节输出流对象 OutputStream os=socket.getOutputStream(); //给客户端写数据 os.write("收到谢谢".getBytes()); //释放资源 socket.close(); server.close(); }