First, a most basic socket application, a simple chat.
//create server ServerSocket server = new ServerSocket(9090); //After waiting for the client connection to enter, after entering, generate a Socket object java.net.Socket client=server.accept(); System.out.println ("Incoming "+client.getRemoteSocketAddress()); //Note: server.accept() is a blocking method, which is blocked on this call. Only when a socket client is connected, this method will have a return value and return the client's socket object, which is the client at this time. The client and server are connected. //Get the input and output stream after connecting to the client OutputStream ops = client.getOutputStream(); InputStream ips = client.getInputStream(); //Note: Write data to the input stream and send it to the client, and write data to the output stream and send it to the server. //Send byte data experiment String s = "Welcome" + username + "come to chat room\r\n"; byte[] b = s.getBytes(); ops.write(b); ops.flush(); String str = readString(ips); while (!str.equals("over")) { System.out.println("Server received: " + str); ChatTools.sendMsg(this.user,str); str = readString(ips); } String n = "Call ended"; ops.write(n.getBytes()); ops.flush(); //Close the connection to the client client.close;
readString is also a blocking method, mainly in ips.read(), this method will have a return value only when the client inputs a character.
private String readString(InputStream ips) throws IOException { StringBuffer sb = new StringBuffer(); char c = 0; //until carriage return is a string while (c != 13) { //delete if (c == 8) { sb.deleteCharAt(sb.length() - 1); c = (char) ips.read(); } else { sb.append(c); c = (char) ips.read(); } } String str = sb.toString().trim(); return str; }
At this time, you can enter telnet locahost 9090 in the command line to connect to the server