Client:
1. Using the Socket class
if (socket = = NULL)
Socket = new Socket (address, 2333);
Do not use ports prior to 1024
2.socket communicates through OutputStream and InputStream operations
if NULL ) new PrintWriter (Socket.getoutputstream ()); Writer.println (tosend); Writer.flush ();//Be sure to remember flush refresh
New BufferedReader (new InputStreamReader (Socket.getinputstream ())); while (! socket.isclosed ()) { sleep (+); = reader.readline (); if (line!=null) { + "\ n");} } Reader.close ();
3. Modify JFrame default Close window event
Addwindowlistener (new Windowadapter () { public void windowclosing (WindowEvent e) { super .windowclosing (e); try { if (Socket! = null ) {so Cket.close (); }} catch (Exception ex) { Ex.printstacktrace (); } system.exit ( 0); } });
Server:
1. Using ServerSocket
New ServerSocket (2333);
2. Broadcast implementation
Socketlist =NewArraylist<socket>(); Try{ServerSocket=NewServerSocket (2333); while(true) {Socket Socket=serversocket.accept (); if(!socketlist.contains (socket)) {Socketlist.add (socket); Newsocketthread (socket); } } } Catch(Exception e) {e.printstacktrace (); }
3. Using multithreading
BufferedReader reader =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); while(socket.isclosed () = =false) {Sleep (100); String Line=Reader.readline (); if(Line! =NULL) { for(inti = 0; I < socketlist.size (); i++) {Socket iter=(Socket) socketlist.get (i); PrintWriter writer=NewPrintWriter (Iter.getoutputstream ()); System.out.println (line); Writer.println (line); Writer.flush (); }}} socketlist.remove (socket);
When I first run the client on my roommate's computer, I can't get access to my server, and I run the firewall after it has been hit by a jar package and then successfully completed the communication!
Java Socket Programming Experiment Summary