官术网_书友最值得收藏!

Reading from the socket

Now, let's check out an example where we will establish a connection to the server with the help of a socket. This will demonstrate how data can be sent and received between the client and the server. The following example is a server application making use of the Socket class to listen to clients on a port number specified by a command-line argument:

//Socket Server

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleSocketServer {
public static void main(String args[]) throws IOException {
// A new service registered with the 1286 port
ServerSocket ss = new ServerSocket(1286);
//Accept the connection request made with the server socket
Socket s=ss.accept();
// Establish the output stream from the socket connection
OutputStream socketOutStream = s.getOutputStream();
DataOutputStream socketDOS = new DataOutputStream
(socketOutStream);
// Communicate with the socket data stream with a message
socketDOS.writeUTF("Hello world!");
// Cleanup
socketDOS.close();
socketOutStream.close();
s.close();
ss.close();
}
}

In the preceding code, we have the SimpleSocketServer class when the main method constructor is invoked. This is where ServerSocket is instantiated with the given port. Further, when the thread starts, the serverSocket.accept() method is invoked and the server starts listening for requests on the given port. After that, when the client sends the request, the server responds and returns the response string to that call.

The following code is a SimpleSocketClient program that connects to SimpleSocketServer. Using the socket, send the test string and then wait for a response from the server that will contain the test string:

//Socket Client

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class SimpleSocketClient {
public static void main(String args[]) throws IOException {
// Establish a server connection through 1286 port
Socket s = new Socket("localhost",1286);
// Access the input stream of the server socket
InputStream sIn = s.getInputStream();
// Wrap the socket input stream with data input stream
DataInputStream socketDIS = new DataInputStream(sIn);
//Read from the socket data input stream
String testString= new String (socketDIS.readUTF());
//Print the data read
System.out.println(testString);
// clean up
socketDIS.close();
sIn.close();
s.close();
}
}

Using the SimpleSocketClient code, you can instantiate Socket() for a given server and port and also establish a connection. After that, the InputStream test string is read from the server socket.

主站蜘蛛池模板: 英吉沙县| 岗巴县| 新化县| 湾仔区| 沁源县| 宿州市| 门头沟区| 云南省| 乐平市| 大宁县| 车致| 翁源县| 徐水县| 米脂县| 龙南县| 桓仁| 拜泉县| 晴隆县| 长治县| 松滋市| 瑞金市| 宁德市| 休宁县| 即墨市| 汨罗市| 大关县| 佛教| 锦屏县| 卫辉市| 茌平县| 新野县| 潢川县| 扎赉特旗| 应用必备| 丘北县| 荣成市| 志丹县| 邵阳县| 肥东县| 滦平县| 德钦县|