Java Socket 通过TCP交互 实例

  Java Socket 编程,分为Socket 和ServerSocket两个类,其中Client 通过构造Socket 实例,向Server 端的ServerSocket发起请求。 ServerSocket 在接受到来自Client 的请求后,构建一个Socket,并将响应内容通过这个Socket实例返回。

   Socket编程可以使用各种不同的传输层协议,本例以TCP协议为例,展示这个交互过程。

   Client:

   

package com.mahoutchina.java.socket.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class TCPEchoClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length < 2 || (args.length > 3)) {
			throw new IllegalArgumentException(
					"Parameter(s):<Server> <Word>[<Port>]");
		}

		String server = args[0];// server name or IP address
		// Convert argument string to bytes using the default character encoding
		String sendData=args[1];
		System.out.println("Data to sent:"+ sendData);
		byte[] data = sendData.getBytes();
		int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;
		System.out.println("Server port:"+servPort);
		
		// create socket that is connected to server on specified port
		Socket socket = null;
		try {
			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);

			// receive
			int totalBytesRcvd = 0;// total bytes received so far
			int bytesRcvd;// Bytes received in last read

			while (totalBytesRcvd < data.length) {
				bytesRcvd = in.read(data, totalBytesRcvd, data.length
						- totalBytesRcvd);
				if (bytesRcvd == -1) {
					throw new SocketException("Connection closed prematurely");
				}
				totalBytesRcvd += bytesRcvd;
			}
			System.out.println("Received:" + new String(data));

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null) {
					socket.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}

服务器端:

    

package com.mahoutchina.java.socket.server;

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 {

	//Size of receive buffer
	private static final int BUFSIZE=32;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//Test for correct # of args
		if(args.length!=1){
			throw new IllegalArgumentException("Parameter(s):<Port>");
		}
		int servPort = Integer.parseInt(args[0]);
		
		//Create a server socket to accept client connection request
		ServerSocket servSocket =null;
		int recvMsgSize=0;
		byte[] receivBuf=new byte[BUFSIZE];
		
		try {
			servSocket=new ServerSocket(servPort);
			while(true){
				Socket clientSocket=servSocket.accept();
				SocketAddress clientAddress = clientSocket.getRemoteSocketAddress();
				System.out.println("Handling client at "+ clientAddress);
				
				InputStream in =clientSocket.getInputStream();
				OutputStream out= clientSocket.getOutputStream();
				
				//receive until client close connection,indicate by -l return
				while((recvMsgSize=in.read(receivBuf))!=-1){
					String receivedData=new String(receivBuf.toString());
					System.out.println(receivedData);
					out.write(receivBuf, 0, recvMsgSize);
				}
				clientSocket.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		

	}

}

  运行:

  先运行server client,配置的参数为9999

  

Handling client at /192.168.1.117:50128

helloEcho


  运行client,参数:localhost helloEcho 999

  

Data to sent:helloEcho

Server port:9999

Connected to server ... sending echo string

Received:helloEcho

     

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

查理曼大帝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值