one. Server-side code:
Import java.net.*; For Socket, ServerSocket, and inetaddress import java.io.*; For IOException and Input/outputstream public class Tcpechoserver {private static final int bufsize =//S
Ize of receive buffer public static void main (string[] args) throws IOException {int servport = 5500;
Create a server socket to accept client connection requests ServerSocket Servsock = new ServerSocket (servport); int recvmsgsize; Size of received message byte[] ReceiveBuf = new Byte[bufsize]; Receive buffer while (true) {//Run forever, accepting and servicing connections Socket Clntsock = Servs Ock.accept ();
Get Client connection SocketAddress clientaddress = clntsock.getremotesocketaddress ();
SYSTEM.OUT.PRINTLN ("Handling client at" + clientaddress);
InputStream in = Clntsock.getinputstream ();
OutputStream out = Clntsock.getoutputstream (); Receive until client closes connectiOn, indicated By-1 return while (recvmsgsize = In.read (receivebuf))!=-1) {out.write (receivebuf, 0, re
Cvmsgsize); } clntsock.close (); Close the socket.
We are done with this client! }/* not reached */}}
two. Client code:
Import java.net.*;
Import java.io.*; public class Tcpechoclient {public static void main (string[] args) throws IOException {String Server = ' 127. 0.0.1 "; Server name or IP address int servport = 5500;
Server Port byte[] data = "Hi, World". GetBytes ();
Create socket: Connected to server on specified port socket = new Socket (server, servport);
System.out.println ("Connected to server...sending Echo string");
InputStream in = Socket.getinputstream ();
OutputStream out = Socket.getoutputstream (); Out.write (data); Send the encoded string to the server//Receive the same string back from the server int TOTALBYTESRCVD = 0; Total Bytes received so far int bytesrcvd; Bytes received in last read while (Totalbytesrcvd < data.length) {if (BYTESRCVD = In.read (data, Totalb YTESRCVD, data.length-totalbytesrcvd) = = = 1) throw new SocketException ("Connection closed Prematurely ");
TOTALBYTESRCVD + = BYTESRCVD;
}//Data array is full SYSTEM.OUT.PRINTLN ("Received:" + new String (data)); Socket.close (); Close the socket and its streams}}
The TCP server for the above code is single-threaded and can only serve one client at a time.
See more Java syntax, you can pay attention to: "Thinking in the Java Chinese manual", "JDK 1.7 reference manual in English," "JDK 1.6 API Java Chinese Reference manual", "JDK 1.5 API Java Chinese Reference manual", also hope that everyone Support the cloud-dwelling community.