Click to enter _ more _java thousand ask
1. How to write a single-threaded socket program
Find out what the socket looks for here: what the socket is
The simplest way to write a socket is a single-threaded socket, but it's basically not practical, because it's basically more than just a client in real-world applications. is usually a multi-threaded socket program.
Learn about multithreaded sockets look here: [How to write multi-threaded socket program][3]
[3]:
To write a socket, you need to understand that the Java.net package provides two classes of sockets and ServerSocket, which are respectively used to represent the client and server side of the socket. Our code is also divided into two parts: client and server.
Service-Side code:
ImportJava.io.BufferedReader;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public class socketsimpledemoserver { Private intPort =8000;//Port PrivateServerSocket ServerSocket; Public Socketsimpledemoserver()throwsException {ServerSocket =NewServerSocket (port); System.out.println ("waitting connet ..."); } Public void Service()throwsIOException {Socket socket =NULL; String msg =NULL; while(true) {//Keep listening until the request is received Try{socket = serversocket.accept ();//Ready to accept the connectionSystem.out.println ("New Connection:"+ socket.getinetaddress () +":"+ Socket.getport ()); BufferedReader reader =NewBufferedReader (NewInputStreamReader (Socket.getinputstream (),"UTF-8"));//input streamPrintWriter writer =NewPrintWriter (Socket.getoutputstream ());//output stream while(msg = Reader.readline ())! =NULL) {//Receive MessagesSystem.out.println ("Receive msg:"+ msg); WRITER.PRINTLN (msg);//Send MessageWriter.flush ();//Note that it is best to force a flush when sending a message using a buffered stream, otherwise the message may not be sent temporarily due to a buffer dissatisfaction if("Close". Equals (msg)) { Break; } } }Catch(Exception e) {E.printstacktrace (); }finally{if(Socket! =NULL) {socket.close (); } } } } Public Static void Main(string[] args)throwsException {NewSocketsimpledemoserver (). Service (); }}
After the service-side code is run, the program listens until a client request is received. The results are as follows:
Waitting connet ...
Client code:
ImportJava.io.BufferedReader;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.Socket; Public class socketdemoclient { PrivateString host ="127.0.0.1";//IP to be sent to the server Private intPort =8000;//port to be sent to the server PrivateSocket socket; Public socketdemoclient()throwsException {socket =NewSocket (host, Port);//construct the socket client and connect to the server} Public void Talk()throwsIOException {Try{BufferedReader reader =NewBufferedReader (NewInputStreamReader (Socket.getinputstream (),"UTF-8")); PrintWriter writer =NewPrintWriter (Socket.getoutputstream ());//Read the local console messageBufferedReader Localreader =NewBufferedReader (NewInputStreamReader (system.in)); String msg =NULL; while(msg = Localreader.readline ())! =NULL) {writer.println (msg); Writer.flush (); System.out.println ("Send msg:"+ Reader.readline ());if("Close". Equals (msg)) { Break; } } }Catch(Exception e) {E.printstacktrace (); }finally{if(Socket! =NULL) {socket.close (); } } } Public Static void Main(string[] args)throwsException {NewSocketdemoclient (). talk (); }}
After running the client-side code, we look at the server console and the following results indicate that the connection was successful:
Waitting connet ...
New Connection:/127.0.0.1:59349
We're going to enter the message we want to send in the console of the client. "Maintain world Peace", when the carriage return is determined, the following results appear on the client console, the message has been sent:
Send msg: Maintaining world Peace
In the console of the server, we will see the following results, stating that the message has been accepted:
Waitting connet ...
New Connection:/127.0.0.1:59349
Receive MSG: Maintaining World Peace
It is important to note that when you select a service port, each port provides a specific service, and the ports do not conflict, including the interface reserved by the system. The port number that is usually 0~1023 is reserved for the system, for example, the port number of the HTTP service for the 80,telnet service is 23 for the port number of the 21,FTP service.
Java thousand asked _02 basic use (011) _ How to write a single-threaded socket program