第2章:基本套接字之TCP套接字
TCP客户端
?
import java.net.Socket;import java.net.SocketException;import java.net.UnknownHostException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class TCPEchoClient {/** * @param args * @throws IOException * @throws UnknownHostException */public static void main(String[] args) throws UnknownHostException, IOException {if (args.length < 2 || args.length > 3)throw new IllegalArgumentException("Parameters:<Server> <Word> [<Port>]");String server = args[0];//server name or ip address//Conver aaargument String to bytes using default character encodingbyte[] data = args[1].getBytes();int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;//Create socket that is connected to server on special portSocket 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 serverint totalByteRcvd = 0; //total bytes received so farint bytesRcvd; //bytes received in last readwhile (totalByteRcvd < data.length) {if((bytesRcvd = in.read(data,totalByteRcvd,data.length-totalByteRcvd)) == -1)throw new SocketException("connection closed prematurely");totalByteRcvd += bytesRcvd;} //data array is fullSystem.out.println("Received:" + new String(data));socket.close();}}?
?
TCP服务器端
?
import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketAddress;public class TCPEchoServer {private static final int BUFSIZE =32; //Size of reveive buffer/** * @param args * @throws IOException */public static void main(String[] args) throws IOException {if(args.length != 1)throw new IllegalArgumentException("Parameter: <Port>");int servPort = Integer.parseInt(args[0]);//create a server socket to accept client connection requestsServerSocket servSocke = new ServerSocket(servPort);int recvMsgSize; //size of receive messagebyte[] receiveBuf = new byte[BUFSIZE]; //receive bufferwhile (true) { //run forever,accepting and servicing connectionsSocket clntSock = servSocke.accept(); //get client connectionSocketAddress 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 returnwhile ((recvMsgSize = in.read(receiveBuf)) != -1) {out.write(receiveBuf,0,recvMsgSize);}clntSock.close(); //close the socket,we are done with this client!}}}?
?
注意:
?
1/TCP终端必须和特定的端口号关联,这样客户端才能够向该端口号发送链接请求
2/端口号第有效范围所0~65535(如果端口号被设为0,将选择任意没有使用第端口号)
?
测试方法:(需要打开2个控制台)
在控制台启动服务器端:输入 ? java TCPEchoServer 8000(也可以所范围内第任意端口)
在控制台启动客户端: ? 输入 ? ?java TCPEchoClient localhost “hello” 8000 (我这里向本地发送tcp请求)
?
我第输出所这样的——
服务器端输出:Handling client at /127.0.0.1:43389
客户端输出:Connected to server ... sending echo stringReceived:hello
成功了。
?
其实可以修改程序固定好服务器,端口号,内容等参数的,这样就不用在控制台里面输入那么多东西了,直接运行服务器端和客户端就行了,很简单的,这里不多说了,有兴趣第朋友可以改好了,发上来交流一下
?
?
?
?
?
?
?
?
?
?
?
?