客户端
1 public class A { 2 public static void main(String[] args) throws IOException { 3 String guo="你好啊"; 4 int port=8888; 5 Socket socket = null; 6 InetAddress ip = InetAddress.getByName("127.0.0.1"); 7 socket=new Socket(ip,port); 8 OutputStream outputStream = socket.getOutputStream(); 9 outputStream.write(guo.getBytes()); 10 socket.close(); 11 outputStream.flush(); 12 outputStream.close(); 13 14 } 15 }
服务器端
public class B { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8888); Socket socket = serverSocket.accept(); InputStream inputStream = socket.getInputStream(); byte[] bytes = new byte[1024]; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int len; while ((len=inputStream.read(bytes))!=-1){ byteArrayOutputStream.write(bytes,0,len); } System.out.println(byteArrayOutputStream.toString()); socket.close(); inputStream.close(); byteArrayOutputStream.flush(); byteArrayOutputStream.close(); } }
标签:outputStream,socket,实现,tcp,聊天,byteArrayOutputStream,close,new,public From: https://www.cnblogs.com/guojianglong/p/17225803.html