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