TCP客户端

来源:互联网 发布:相声是什么知乎 编辑:程序博客网 时间:2024/05/19 13:43
package com.logic;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.SocketException;/*传输大致分三个阶段 * step1:建立链接 * step2:数据传输 * step3:关闭链接 * *//* * step1:首先,客户端要去访问服务器,那么你必须要知道服务器的名字或者IP地址。好比,你想拜访我,你总的知道我叫啥,住在哪儿吧。 * 客户端根据已知的服务器名称和端口号(不知道端口号就使用服务器默认端口号)创建一个socket。 * 在socket的基础上创建I/O流。将要传输的数据通过outputstream发送给服务器。 * 服务器在获取了客户端的请求后,根据客户端的IP地址和端口号也创建一个服务器端的socket端口。同时也创建I/O流。并且将相应信息反馈给 * 客户端接收到服务器的链接同意后再次回应服务器,表示我已经收到了。此时服务器处于监听的状态,等待客户端的数据。 * 这期间经历了三次握手,客户端两次,服务器端一次。 * 断开连接时同样也要经历三次握手。 */public class TCPEchoClient {public static void main(String[] args) throws IOException{if ((args.length < 2) || args.length > 3){System.out.println("input error!");}/*step1*///server name or IP addressString server = args[0];//convert argument String to bytes using the default character encodingbyte[] data = args[1].getBytes();//confirm the port, default port is 7.int servPort;if (args.length == 3){servPort = Integer.parseInt(args[2]);}else{servPort = 7;}//int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;//create socket that is connected to server on specified portSocket socket = new Socket(server, servPort);System.out.println("Connected to server...sending echo string");/*step2*/InputStream in = socket.getInputStream();OutputStream out = socket.getOutputStream();//sending encoded string to the server.the connection has been established.out.write(data);//receive the same string back form the serverint totalBytesRcvd = 0;int bytesRcvd;while (totalBytesRcvd < data.length){if ((bytesRcvd = in.read(data, totalBytesRcvd, data.length - totalBytesRcvd)) == -1){throw new SocketException("Connection closed prematurely");}totalBytesRcvd += bytesRcvd;}System.out.println("Received: " + new String(data));socket.close();}}

原创粉丝点击