Java Network Programming from entry to mastery (26): receive and send data on the server

Source: Internet
Author: User

After creationServerSocketAfter the objectAcceptMethod returnSocketObject, the server can interact with the client.

SocketClass andServerSocketThe class has two methods to get the input and output streams:GetInputStreamAndGetOutputStream. ForSocketClass, useGetInputStreamMethodInputStreamIs to obtain data from the server, andGetOutputStreamMethodOutputStreamIs to send data to the server. WhileServerSocketOfGetInputStreamAndGetOutputStreamThe method is similar.InputStreamRead data from the client,OutputStreamSend data to the client. The following codeIs a receiptHTTPRequest and returnHTTPThe request header information program, which demonstratesServerSocketClass to read and send data from the client.

Package Server;

Import Java.net. * ;
Import Java. io. * ;

Public   Class HttpEchoServer Extends Thread
{
Private Socket socket;
Public   Void Run ()
{
Try
{
InputStreamReader isr =   New InputStreamReader (socket
. GetInputStream ());
BufferedReader br =   New BufferedReader (isr );
OutputStreamWriter osw =   New OutputStreamWriter (socket
. GetOutputStream ());
Osw. write ( " HTTP/1.1 200 OK " );
String s =   "" ;
While ( ! (S = Br. readLine (). equals ( "" ))
Osw. write ( " <Html> <body> "   + S +   " <Br> </body> " );
Osw. flush ();
Socket. close ();
}
Catch (Exception e)
{
}
}
Public HttpEchoServer (Socket socket)
{
This . Socket = Socket;
}
Public   Static   Void Main (String [] args) Throws Exception
{
ServerSocket serverSocket =   New ServerSocket ( 8888 );
System. out. println ( " The server has been started. Port: 8888 " );
& Nbs

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.