[size=13.63636302948px]8、TCP客户端
[size=13.63636302948px] 在Socket编程中,首先客户端需要向服务器端发送,然后被动的等待服务器端的响应。下面的示例中:我们向服务器端发送信息,等待服务器端发送的消息,并打印显示出来。
[size=13.63636302948px]import java.io.IOException;
[size=13.63636302948px]import java.io.InputStream;
[size=13.63636302948px]import java.io.OutputStream;
[size=13.63636302948px]import java.net.Socket;
[size=13.63636302948px]import java.net.SocketException;
[size=13.63636302948px]public class TCPEchoClient {
[size=13.63636302948px] public static void main(String[] args) throws IOException {
[size=13.63636302948px] // 判断从控制台接受的参数是否正确
[size=13.63636302948px] if ((args.length < 2) || (args.length > 3))
[size=13.63636302948px] throw new IllegalArgumentException("Parameter(s):<Server><Word>[<Port>]]");
[size=13.63636302948px] // 获取服务器地址
[size=13.63636302948px] String server = args[0];
[size=13.63636302948px] // 获取需要发送的信息
[size=13.63636302948px] byte[] data = args[1].getBytes();
[size=13.63636302948px] // 如果有三个从参数那么就获取发送信息的端口号,默认端口号为8099
[size=13.63636302948px] int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 8099;
[size=13.63636302948px] // 根据服务器地址和端口号实例化一个Socket实例
[size=13.63636302948px] Socket socket = new Socket(server, servPort);
[size=13.63636302948px] System.out.println("Connectedtoserver...sendingechostring");
[size=13.63636302948px] // 返回此套接字的输入流,即从服务器接受的数据对象
[size=13.63636302948px] InputStream in = socket.getInputStream();
[size=13.63636302948px] // 返回此套接字的输出流,即向服务器发送的数据对象
[size=13.63636302948px] OutputStream out = socket.getOutputStream();
[size=13.63636302948px] // 向服务器发送从控制台接收的数据
[size=13.63636302948px] out.write(data);
[size=13.63636302948px] // 接收数据的计数器,将写入数据的初始偏移量
[size=13.63636302948px] int totalBytesRcvd = 0;
[size=13.63636302948px] // 初始化接收数据的总字节数
[size=13.63636302948px] int bytesRcvd;
[size=13.63636302948px] while (totalBytesRcvd < data.length) {
[size=13.63636302948px] // 服务器关闭连接,则返回-1,read方法返回接收数据的总字节数
[size=13.63636302948px] if ((bytesRcvd = in.read(data, totalBytesRcvd, data.length - totalBytesRcvd)) == -1)
[size=13.63636302948px] throw new SocketException("与服务器的连接已关闭");
[size=13.63636302948px] totalBytesRcvd += bytesRcvd;
[size=13.63636302948px] }
[size=13.63636302948px] // 打印服务器发送来的数据
[size=13.63636302948px] System.out.println("Received:" + new String(data));
[size=13.63636302948px] // 关闭连接
[size=13.63636302948px] socket.close();
[size=13.63636302948px] }
[size=13.63636302948px]}
9、运行结果
[size=13.63636302948px]首先运行服务器端,监听8099端口:
接着运行客户端程序,并且向服务器端发送消息:
再次查看我们的服务器端控制台,我们可以看到前面客户端连接的地址信息:
[img]file:///C:/Users/Administrator/Documents/My%20Knowledge/temp/d42d5f43-7438-45f2-8614-e7791fb98c95_4_files/20140122163217[1].jpg[/img]
|