Customer/server interaction in the form of stream socket connection

Source: Internet
Author: User

Import java. AWT. borderlayout;
Import java. AWT. container;
Import java. AWT. event. actionevent;
Import java. AWT. event. actionlistener;
Import java. Io. eofexception;
Import java. Io. ioexception;
Import java. Io. objectinputstream;
Import java. Io. objectoutputstream;
Import java.net. serversocket;
Import java.net. Socket;

Import javax. Swing. jframe;
Import javax. Swing. jscrollpane;
Import javax. Swing. jtextarea;
Import javax. Swing. jtextfield;
Import javax. Swing. swingutilities;

// Server type
Public class Server extends jframe {
Private Static final long serialversionuid = 1l;

Private jtextfield enterfield; // input dialog box
Private jtextarea displayarea; // display content
Private objectoutputstream output; // output stream
Private objectinputstream input; // input stream
Private serversocket server; // Server Object
Private socket connection; // connection object
Private int counter = 1;

Public server (){
Super ("server ");

Container = getcontentpane ();

Enterfield = new jtextfield ();
Enterfield. seteditable (false );
Enterfield. addactionlistener (New actionlistener (){
Public void actionreceivmed (actionevent event ){
Senddata (event. getactioncommand (); // send data
Enterfield. settext ("");
}
});

Container. Add (enterfield, borderlayout. North );

Displayarea = new jtextarea ();
Container. Add (New jscrollpane (displayarea), borderlayout. center );

Setsize (300,150 );
Setvisible (true );
}

Public void runserver (){
Try {
Server = new serversocket (12345,100); // create a Server Object with port 12345 and a maximum of 100 connections

While (true ){
Waitforconnection (); // wait for the connection
Getstreams (); // receives and sends bytes.
Processconnection (); // process input and output for communication
}
} Catch (eofexception ){
// Todo: handle exception
System. Err. println ("server terminated connection ");
} Catch (ioexception ){
// Todo: handle exception
Ioexception. printstacktrace ();
}
Finally {
Closeconnection (); // close the connection
++ Counter;
}
}

Private void waitforconnection () throws ioexception {
Displaymessage ("waiting for connection/N ");
Connection = server. Accept (); // listen to the customer's connection
Displaymessage ("connection" + counter + "received from :"
+ Connection. getinetaddress (). gethostname (); // obtain the client name.
}
 
Private void getstreams () throws ioexception {
Output = new objectoutputstream (connection. getoutputstream (); // get the output stream
Output. Flush (); // refresh the buffer

Input = new objectinputstream (connection. getinputstream (); // get the input stream

Displaymessage ("/ngot I/O streams/N ");
}
 
Private void processconnection () throws ioexception {
String message = "connection successful ";
Senddata (Message );

Settextfieldeditable (true );

Do {
Try {
Message = (string) Input. readobject (); // obtain the input information.
Displaymessage ("/N" + message );
} Catch (classnotfoundexception ){
// Todo: handle exception
Displaymessage ("/nunknow object type already ed ");
}
} While (! Message. Equals ("client >>> terminate"); // terminate ends
}
 
Private void closeconnection (){
Displaymessage ("/nterminating connection/N ");
Settextfieldeditable (false );

Try {
Output. Close ();
Input. Close ();
Connection. Close ();
} Catch (ioexception ){
// Todo: handle exception
Ioexception. printstacktrace ();
}
}
 
Private void senddata (string message ){
Try {
Output. writeobject ("server >>>" + message); // write data
Output. Flush ();
Displaymessage ("/nserver >>>" + message );
} Catch (ioexception ){
// Todo: handle exception
Displayarea. append ("/nerror writing object ");
}
}
 
Private void displaymessage (final string messagetodisplay ){
Swingutilities. invokelater (New runnable () {// internal class, so that the content can be correctly displayed in the thread
Public void run (){
Displayarea. append (messagetodisplay );
Displayarea. setcaretposition (displayarea. gettext (). Length (); // After the cursor is positioned to the last character
}
});
}
 
Private void settextfieldeditable (final Boolean editable ){
Swingutilities. invokelater (New runnable (){
Public void run (){
Enterfield. seteditable (editable );
}
});
}

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Server application = new server ();
Application. setdefaclocloseoperation (jframe. exit_on_close );
Application. runserver ();
}

}

 

 

 

 

Package classwork;

Import java. AWT. borderlayout;
Import java. AWT. container;
Import java. AWT. event. actionevent;
Import java. AWT. event. actionlistener;
Import java. Io. eofexception;
Import java. Io. ioexception;
Import java. Io. objectinputstream;
Import java. Io. objectoutputstream;
Import java.net. inetaddress;
Import java.net. Socket;

Import javax. Swing. jframe;
Import javax. Swing. jscrollpane;
Import javax. Swing. jtextarea;
Import javax. Swing. jtextfield;
Import javax. Swing. swingutilities;

// Customer class
Public class Client extends jframe {
Private Static final long serialversionuid = 1l;

Private jtextfield enterfield;
Private jtextarea displayarea;
Private objectoutputstream output;
Private objectinputstream input;
Private Socket Client;
Private string chatserver;
Private string message = "";
 
Public client (string host ){
Super ("client ");

Chatserver = host; // server address

Container = getcontentpane ();

Enterfield = new jtextfield ();
Enterfield. seteditable (false );
Enterfield. addactionlistener (New actionlistener (){
Public void actionreceivmed (actionevent event ){
Senddata (event. getactioncommand ());
Enterfield. settext ("");
}
});

Container. Add (enterfield, borderlayout. North );

Displayarea = new jtextarea ();
Container. Add (New jscrollpane (displayarea), borderlayout. center );

Setsize (300,150 );
Setvisible (true );
}
 
Private void runclient (){
Try {
Connecttoserver (); // create a socket and prepare for connection
Getstreams ();
Processconnection ();
} Catch (eofexception ){
// Todo: handle exception
System. Err. println ("client terminated connection ");
} Catch (ioexception ){
// Todo: handle exception
Ioexception. printstacktrace ();
}

Finally {
Closeconnection ();
}
}
 
Private void connecttoserver () throws ioexception {
Displaymessage ("attempting connection/N ");

Client = new socket (inetaddress. getbyname (chatserver), 12345); // connect to the server

Displaymessage ("connected to:" + client. getinetaddress (). gethostname ());
}
 
Private void getstreams () throws ioexception {
Output = new objectoutputstream (client. getoutputstream ());
Output. Flush ();

Input = new objectinputstream (client. getinputstream ());

Displaymessage ("/ngot I/O streams/N ");
}
 
Private void processconnection () throws ioexception {
Settextfieldeditable (true );

Do {
Try {
Message = (string) Input. readobject ();
Displaymessage ("/N" + message );
} Catch (classnotfoundexception ){
// Todo: handle exception
Displaymessage ("/nunknow object type already ed ");
}
} While (! Message. Equals ("server >>> terminate "));
}
 
Private void closeconnection (){
Displaymessage ("/nclosing connection ");
Settextfieldeditable (false );

Try {
Output. Close ();
Input. Close ();
Client. Close ();
} Catch (ioexception ){
// Todo: handle exception
Ioexception. printstacktrace ();
}
}
 
Private void senddata (string message ){
Try {
Output. writeobject ("client >>>" + message );
Output. Flush ();
Displaymessage ("/nclient >>>" + message );
} Catch (ioexception ){
// Todo: handle exception
Displayarea. append ("/nerror writing object ");
}
}
 
Private void displaymessage (final string messagetodisplay ){
Swingutilities. invokelater (New runnable (){
Public void run (){
Displayarea. append (messagetodisplay );
Displayarea. setcaretposition (displayarea. gettext (). Length ());
}
});
}
 
Private void settextfieldeditable (final Boolean editable ){
Swingutilities. invokelater (New runnable (){
Public void run (){
Enterfield. seteditable (editable );
}
});
}
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Client application;

If (ARGs. Length = 0) // if no Server IP address is specified, it communicates with the Local Computer and localhost is used for testing.
Application = new client ("127.0.0.1 ");
Else
Application = new client (ARGs [0]);

Application. setdefaclocloseoperation (jframe. exit_on_close );
Application. runclient ();
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.