Android socket programming, chat as an example of http://hi.baidu.com/yaoyuanhuajx/item/9b93d7565f315ba9acc857d7

Source: Internet
Author: User
Tags sendmsg
Step by step Android (15): socket programming [chat as an example]

In addition to its mobile phone functions, the Android mobile phone app is also attractive because of its openness. This iPhone is incomparable, at least it is too commercialized.

Like Windows 95, Android opened another window for communication, and socket communication was essential to achieve communication.

Java already has a good example of socket communication. I just introduced it into Android. omissions are inevitable, and many places are worth pondering and consideration, skip this article.

Next, we will use a knock-on method to demonstrate how android can implement socket communication.

This example provides the following functions:

Enable services on the server
The client initiates a connection request and sends data to the server.
The server responds to the request and displays it on the server, and returns data to the client.
The client receives and displays the server data.

In this example, the effect is as follows:

Terminal 1:

 

Terminal 2:

 

Server:

The source code of this example is as follows:

Server:

Package com. Android. Yao;

Import java. Io. bufferedreader;
Import java. Io. bufferedwriter;
Import java. Io. ioexception;
Import java. Io. inputstreamreader;
Import java. Io. outputstreamwriter;
Import java.net. serversocket;
Import java.net. Socket;

Public class yaochatserver extends thread {

Private yaochatserver () throws ioexception {
Createsocket ();
// Create a socket server
}

Public void run (){
Socket Client;
String txt;
Try {
While (true)
// Infinite thread loop, real-time listening to socket ports
{
Client = responsesocket ();
// Respond to the client connection request ..

While (true)
{
TXT = receivemsg (client );
System. Out. println (txt );
// Obtain the message sent from the client and display it on the server screen

Sendmsg (client, txt );
// Return a message to the client

If (true) break;
// Interrupted. Wait for the link request
}

Closesocket (client );
// Close this link
}
}
Catch (ioexception e ){
System. Out. println (E );
}

}

Private serversocket Server = NULL;
Private Static final int Port = 5000;
Private bufferedwriter writer;
Private bufferedreader reader;

Private void createsocket () throws ioexception
{
Server = new serversocket (port, 100 );
System. Out. println ("server starting ..");
}

Private socket responsesocket () throws ioexception
{
Socket Client = server. Accept ();
System. Out. println ("Client Connected ..");

Return client;
}

Private void closesocket (Socket socket) throws ioexception
{
Reader. Close ();
Writer. Close ();
Socket. Close ();
System. Out. println ("client closed ..");
}

Private void sendmsg (Socket socket, string MSG) throws ioexception
{
Writer = new bufferedwriter (
New outputstreamwriter (socket. getoutputstream ()));
Writer. Write (MSG + "\ n ");
Writer. Flush ();

}

Private string receivemsg (Socket socket) throws ioexception
{
Reader = new bufferedreader (
New inputstreamreader (socket. getinputstream ()));
System. Out. println ("server get input from client socket ..");
String TXT = "sever send:" + reader. Readline ();

Return txt;
}

Public static void main (final string ARGs []) throws ioexception {
Yaochatserver = new yaochatserver ();
If (yaochatserver! = NULL ){
Yaochatserver. Start ();
}
}

}

 

Client:

Package com. Android. Yao;

Import java. Io. bufferedreader;
Import java. Io. bufferedwriter;
Import java. Io. ioexception;
Import java.net. unknownhostexception;

Import java. Io. inputstreamreader;
Import java. Io. outputstreamwriter;
Import java.net. Socket;
Import Android. App. activity;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. widget .*;

Public class yaochatroomandroid extends activity {
/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. chatroom );

Findviews ();
Setonclick ();

}

Private edittext chattxt;
Private textview chattxt2;
Private button chatok;

Public void findviews ()
{
Chattxt = (edittext) This. findviewbyid (R. Id. chattxt );
Chattxt2 = (textview) This. findviewbyid (R. Id. chattxt2 );
Chatok = (button) This. findviewbyid (R. Id. chatok );
}

Private void setonclick ()
{
Chatok. setonclicklistener (New View. onclicklistener (){

@ Override
Public void onclick (view v ){
Try {
Connecttoserver (chattxt. gettext (). tostring ());
} Catch (unknownhostexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (ioexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
});
}

Public void connecttoserver (string socketdata) throws unknownhostexception, ioexception
{
Socket socket = requestsocket ("192.168.0.107", 5000 );
Sendmsg (socket, socketdata );
String TXT = receivemsg (socket );
This. chattxt2.settext (txt );
}


Private socket requestsocket (string host, int port) throws unknownhostexception, ioexception
{
Socket socket = new socket (host, Port );
Return socket;
}

Private void sendmsg (Socket socket, string MSG) throws ioexception
{
Bufferedwriter writer = new bufferedwriter (New outputstreamwriter (socket. getoutputstream ()));
Writer. Write (msg. Replace ("\ n", "") + "\ n ");
Writer. Flush ();
}

Private string receivemsg (Socket socket) throws ioexception
{
Bufferedreader reader = new bufferedreader (New inputstreamreader (socket. getinputstream ()));

String TXT = reader. Readline ();
Return txt;

}
}

Related Article

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.