1. Server-side
Import Java.io.bufferedreader;import Java.io.ioexception;import java.io.inputstream;import Java.io.inputstreamreader;import Java.net.serversocket;import Java.net.Socket; Public classHelloworldserver { Public Static voidMain (string[] args) {ServerSocket server=NULL; BufferedReader Reader=NULL; Socket Client=NULL; Try{Server=NewServerSocket (9000);//Create a ServerSocket object and bind the port client=server.accept ();//Call the Accept method, waiting for the client to connect InputStreaminch=Client.getinputstream (); Reader=NewBufferedReader (NewInputStreamReader (inch)); String Str=Reader.readline (); System. out. println (str); } Catch(IOException e) {e.printstacktrace (); }finally{ Try{ if(client!=NULL) {client.close (); } }Catch(IOException e) {e.printstacktrace (); } } }}
2. Client
import java.io.ioexception;import java.io.outputstream;import java.io.printwriter;import java.net.Socket; Import Java.net.unknownhostexception;import Java.util.Scanner; Public classhelloworldclient { Public Static voidMain (string[] args) {Socket client=NULL; PrintWriter writer=NULL; Try{Client=NewSocket ("www.feifeishi.cn",9000);//www.feifeishi.cn is my cloud server OutputStream out=Client.getoutputstream (); Writer=NewPrintWriter ( out); Scanner SC=NewScanner (System.inch); String AA=Sc.nextline (); Writer.print (AA); Writer.flush (); } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{ Try{ if(writer!=NULL) {writer.close (); } if(client!=NULL) {client.close (); } }Catch(IOException e) {e.printstacktrace (); } } }}
3. Running
Put the server side on the server and run
Run server-side
Waiting for client access, then running the client locally
Console input Hello, and then the server side receives and displays Hello
4. Expand
The core idea of TCP programming Java.net.Socket Java.net.ServerSocketTCP Programming Server-side ServerSocket ss = new ServerSocket (9000) ss.accept ( );socket s = new socket ("150.236.56.101", 9000)
Java network programming, simple client and server side