import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; public class TCPServer { private static final int RECV_BUF_SIZE = 1024; public static void main(String[] args) throws Exception { int servPort = 8088; ServerSocket servSock = new ServerSocket(servPort); int recvMsgSize; byte[] receiveBuf = new byte[RECV_BUF_SIZE]; while (true) { Socket clntSock = servSock.accept(); SocketAddress clientAddress = clntSock.getRemoteSocketAddress(); System.out.println("Handling client at " + clientAddress); InputStream in = clntSock.getInputStream(); OutputStream out = clntSock.getOutputStream(); while ((recvMsgSize = in.read(receiveBuf)) != -1) { out.write(receiveBuf, 0, recvMsgSize); } clntSock.close(); } } }
import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class TCPClient { public static void main(String[] args) throws Exception { String server = "127.0.0.1"; byte[] data = "Hello World!".getBytes(); int servPort = 8088; Socket socket = new Socket(server, servPort); System.out.println("Connecting to server…"); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); out.write(data); int totalBytesRcvd = 0; int bytesRcvd; while (totalBytesRcvd < data.length) { bytesRcvd = in.read(data, totalBytesRcvd, data.length - totalBytesRcvd); totalBytesRcvd += bytesRcvd; } System.out.println("Received: " + new String(data)); socket.close(); } }