欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

TCP通信

程序员文章站 2022-03-04 08:49:56
...

TCP通信的一个模板

TCP的服务端用while一直接收客户端的发送的请求连接

在服务端接受到消息之后,客户端并不知道服务端的情况,还原样发回去,这里客户端接受到服务端得信息的是很才知道服务端已经接受到了客户端的发送的信息

这面是我的写的一个简单的TCP通信原理的例子

服务端

package com.lzb.common.socket;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * 
 * 功能描述:TCP服务端
 *
 * @author  lizhenbin
 *
 * <p>修改历史:(修改人,修改时间,修改原因/内容)</p>
 */
public class TcpServer {
	
	public static boolean isRunning = true;
	
	private static TcpServer instance = null;
	public TcpServer() {};
	public static synchronized TcpServer getInstance() {
		if(instance == null)
			instance = new TcpServer();
		return instance;
	}
	
	/**
	 * 
	 * 功能描述:TCP服务器初始化
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-9 下午7:38:37</p>
	 *
	 * @param port
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public boolean server(String port) {
		
		if(port==null || port.equals("")) {
			System.out.println("Usage: TCP Server Port is Null.");
			return false;
		}
		
		ServerSocket ss = null;
		try {
			ss = new ServerSocket(Integer.valueOf(port));
			while(isRunning) {
				Socket socket = ss.accept();
				TcpServerTaskThread taskThread = new TcpServerTaskThread(socket);
				new Thread(taskThread).start();
			}
			ss.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				ss.close();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}	
		}
	}
	
	public static void main(String[] args) {
		
		TcpServer tcp = TcpServer.getInstance();
		tcp.server("3000");
		
	}

}

 

服务端的任务线程

/**
 * TcpServerTaskThread.java	  V1.0   2012-5-9 下午6:14:15
 *
 * Copyright Lizhenbin Co. ,Ltd. All rights reserved.
 *
 * Modification history(By    Time    Reason):
 * 
 * Description:
 */

package com.lzb.common.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.Callable;
/**
 * 
 * 功能描述:TCP服务端处理线程,接收到的任务数据,在传回去给客户端
 *
 * @author  lizhenbin
 *
 * <p>修改历史:(修改人,修改时间,修改原因/内容)</p>
 */
public class TcpServerTaskThread implements Runnable {
	
	private Socket socket = null;
	
	public TcpServerTaskThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		
		InputStream ins = null;
		BufferedReader buf = null;
		OutputStream outs = null;
		PrintWriter pw = null;
		try {
			while(true) {
				/**
				 * TCP服务端程序接受客户端部分
				 */
				ins = this.socket.getInputStream();
				buf = new BufferedReader(new InputStreamReader(ins));
				/**
				 * 获取客户端发送的信息
				 */
				String msg = buf.readLine();
				if(msg==null)
					break;
				System.out.println("TCP Server Usage: " + msg);
				/**
				 * TCP服务端向客户端发送接收到的消息
				 */
				outs = socket.getOutputStream();
				pw = new PrintWriter(outs, true);
				pw.println(msg);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				buf.close();
				ins.close();
				pw.close();
				outs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

 

客户端的程序

/**
 * TcpCient.java	  V1.0   2012-5-9 下午6:57:51
 *
 * Copyright Lizhenbin Co. ,Ltd. All rights reserved.
 *
 * Modification history(By    Time    Reason):
 * 
 * Description:
 */

package com.lzb.common.socket;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

import com.lzb.common.EntityChanageXmlJson;
/**
 * 
 * 功能描述:TCP客户端
 *
 * @author  lizhenbin
 *
 * <p>修改历史:(修改人,修改时间,修改原因/内容)</p>
 */
public class TcpClient {
	
	/**
	 * 
	 * 功能描述:TCP客户端初始化
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :2012-5-9 下午7:41:18</p>
	 *
	 * @param msg
	 * @param iphost
	 * @param port
	 * @return
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public boolean init(String msg, String iphost, String port) {
		
		if(msg==null || msg.equals("")) {
			System.out.println("Usage: TCP Client Send Message is Null.");
			return false;
		}
		if(iphost==null || iphost.equals("")) {
			System.out.println("Usage: TCP Client IP Host is Null.");
			return false;
		}
		if(port==null || port.equals("")) {
			System.out.println("Usage: TCP Client Listener Port is Null.");
			return false;
		}
		
		Socket socket = null;
		OutputStream outs = null;
		PrintWriter pw = null;
		InputStream ins = null;
		BufferedReader buf = null;
		try {
			socket = new Socket(iphost, Integer.valueOf(port));
			/**
			 * 向TCP服务端发送数据部分
			 */
			outs = socket.getOutputStream();
			pw = new PrintWriter(outs, true);
			pw.println(msg);
			
			/**
			 * 接收TCP服务端反馈回来的消息
			 */
			ins = socket.getInputStream();
			buf = new BufferedReader(new InputStreamReader(ins));
			System.out.println("TCP Client Usage: " + buf.readLine());
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			pw.close();
			try {
				outs.close();
				pw.close();
				buf.close();
				ins.close();
				socket.close();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
	}
	
}

 

 

 

 

 

 

 

 

 

 

 

<——————————————————      old version   ————————————————————————>

 

 

最近离职,回家修养顺便考试,考试结束之后无聊时间写了一下TCP通信的简单例子。

实现TCP通信,首先建立服务断,我这里用到while循环,用于接受客户端的请求。

客户端程序:

 

/**
 * TcpServerThread.java	  V1.0   Apr 26, 2012 10:33:06 PM
 *
 * Copyright Lizhenbin Co. ,Ltd. All rights reserved.
 *
 * Modification history(By    Time    Reason):
 * 
 * Description:
 */

package com.tcp.server;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

import com.tcp.vo.TcpVO;

public class TcpServerThread implements Runnable {
	
	private Socket socket = null;
	
	public TcpServerThread() {};
	
	public TcpServerThread(Socket socket) {
		
		this.socket = socket;
	}
	
	public void run() {
		
		try {	
			
			// 接收到服务端发到的信息
			InputStream ins = socket.getInputStream();
			BufferedReader buf = new BufferedReader(new InputStreamReader(ins));
			
			// 接收到数据后发送消息给客户端
			OutputStream outs = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(outs, true);
			
			// 接收客户端发送的vo信息
			ObjectInputStream ois = new ObjectInputStream(ins);
			// 发送反馈消息给客户端
			ObjectOutputStream objOuts = new ObjectOutputStream(outs);
			
			boolean isRunning = true;
				while(isRunning) {
					
					TcpVO vo = new TcpVO();
					vo = (TcpVO) ois.readObject();
					System.out.println("Server------->Id: " + vo.getId());
					System.out.println("Server------->Name: " + vo.getName());
					System.out.println("Server------->Create Time: " + vo.getCtime());
					
					// 发送反馈消息给客户端
					objOuts.writeObject(vo);
					
//					// 在服务端输出客户端发过来的信息
//					String clinetMsg = buf.readLine();
//					System.out.println("Server---->Clinet Port: " + socket.getPort() + "----->Msg: " + clinetMsg);
//					
//					String revStr = (new StringBuffer(clinetMsg).reverse()).toString();
//					// 服务端发送给客户端的信息
//					pw.println("Client-------------->" + revStr);
				}
			pw.close();
			outs.close();
			buf.close();
			ins.close();
			ois.close();
			objOuts.close();			
			
		} catch (Exception e) {
			//e.printStackTrace();
			if(e instanceof NullPointerException) {
				System.out.println("---------->Port: " + socket.getPort() + " finished.");
			}
		}
	}

}

 

启动服务端的程序:

/**
 * TcpServer.java	  V1.0   Apr 26, 2012 10:16:10 PM
 *
 * Copyright Lizhenbin Co. ,Ltd. All rights reserved.
 *
 * Modification history(By    Time    Reason):
 * 
 * Description:
 */

package com.tcp.server;

import java.net.ServerSocket;
import java.net.Socket;

import com.tcp.util.BaseConfig;

public class TcpServer extends BaseConfig {
	
	/* 开启服务端信息 */ 
	private ServerSocket ServerSocket = null;
	private String ipAddress = null;
	private Integer port;
	
	/**
	 * 
	 * 功能描述:创建服务端TCP
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :Apr 26, 2012 11:42:25 PM</p>
	 *
	 * @throws Exception
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public void initSocket() throws Exception {
		
		// 验证参数
		if(this.getConfigMap()==null) {
			System.out.println("Usage: Read Config Property is NULL.");
			return;
		}
		this.ipAddress = (String) this.getConfigMap().get("server.host");
		if(this.ipAddress==null) {
			System.out.println("Usage: TCP IP Address is NULL.");
			return;
		}
		String portStr = (String) this.getConfigMap().get("server.port");
		if(portStr==null) {
			System.out.println("Usage: TCP Port is NULL.");
			return;
		}
		this.port = Integer.valueOf(portStr);
		ServerSocket = new ServerSocket(this.port);
		Socket socket = null;
		
		boolean isRunning = true;
		while(isRunning) {
			
			socket = ServerSocket.accept();
			TcpServerThread tcpServer = new TcpServerThread(socket);
			Thread thread = new Thread(tcpServer);
			thread.start();
		}
		socket.close();
		ServerSocket.close();
		
	}

	/**
	 * 功能描述:执行线程
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :Apr 26, 2012 10:16:17 PM</p>
	 *
	 * @param args
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static void main(String[] args) {
		
		TcpServer tcpServer = new TcpServer();
		try {
			tcpServer.initSocket();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

 

客户端程序

/**
 * ClientServerThread.java	  V1.0   Apr 26, 2012 11:48:51 PM
 *
 * Copyright Lizhenbin Co. ,Ltd. All rights reserved.
 *
 * Modification history(By    Time    Reason):
 * 
 * Description:
 */

package com.tcp.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.tcp.vo.TcpVO;

public class ClientServerThread implements Runnable {
	
	/* 开启服务端信息 */ 
	private String ipAddress = null;
	private Integer port;
	private String pk;

	public ClientServerThread() {
		super();
	}
	
	public ClientServerThread(String ipAddress, Integer port, String pk) {
		super();
		this.ipAddress = ipAddress;
		this.port = port;
		this.pk = pk;
	}

	public void run() {
		
		int count = 0;
		try {
			Socket socket = new Socket(ipAddress, port);
			
			// 客户端发送数据给服务端
			OutputStream outs = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(outs, true);
			// 接收服务器端返回的数据
			InputStream ins = socket.getInputStream();
			
			// 客户端发送VO
			ObjectOutputStream objOuts = new ObjectOutputStream(outs);
			// 接收客户端发送的vo信息
			ObjectInputStream ois = new ObjectInputStream(ins);
			
			boolean isRunning = true;			
			while(isRunning) {
				
				TcpVO vo = new TcpVO();
				vo.setId(pk);
				vo.setName("李真斌(ch-zn), lizhenbin(en) " + count + " 次");
				DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				vo.setCtime(df.parse(df.format(new Date())));
				objOuts.writeObject(vo);
				
				Thread.sleep(1000);
				
				count++;
//				pw.println("-------->执行该客户端的当前线程: " + Thread.currentThread().getName() + " 执行: " + count + " 次");
//				
//				
//				BufferedReader buf = new BufferedReader(new InputStreamReader(ins));
//				String recvStr = buf.readLine();
//				System.out.println("------->客户端接收到的返回信息: " + recvStr);
				
				TcpVO revVo = (TcpVO) ois.readObject();
				System.out.println("Clinet------->Id: " + revVo.getId());
				System.out.println("Clinet------->Name: " + revVo.getName());
				System.out.println("Clinet------->Create Time: " + revVo.getCtime());
			
			}
			
			pw.close();
			outs.close();
			socket.close();
			ins.close();
			ois.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getIpAddress() {
		return ipAddress;
	}

	public void setIpAddress(String ipAddress) {
		this.ipAddress = ipAddress;
	}

	public Integer getPort() {
		return port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}

	public String getPk() {
		return pk;
	}

	public void setPk(String pk) {
		this.pk = pk;
	}

}

 

启动客户端程序

/**
 * ClientServer.java	  V1.0   Apr 26, 2012 11:47:42 PM
 *
 * Copyright Lizhenbin Co. ,Ltd. All rights reserved.
 *
 * Modification history(By    Time    Reason):
 * 
 * Description:
 */

package com.tcp.client;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.tcp.util.BaseConfig;

public class ClientServer extends BaseConfig {
	
	/* 开启服务端信息 */ 
	private String ipAddress = null;
	private Integer port;
	
	public void initSocket() throws Exception {
		
		// 验证参数
		if(this.getConfigMap()==null) {
			System.out.println("Usage: Read Config Property is NULL.");
			return;
		}
		this.ipAddress = (String) this.getConfigMap().get("server.host");
		if(this.ipAddress==null) {
			System.out.println("Usage: TCP IP Address is NULL.");
			return;
		}
		String portStr = (String) this.getConfigMap().get("server.port");
		if(portStr==null) {
			System.out.println("Usage: TCP Port is NULL.");
			return;
		}
		this.port = Integer.valueOf(portStr);
		
		ExecutorService exec = Executors.newSingleThreadExecutor();
		//for(int i=0; i<5; i++) {
			
			ClientServerThread clientServerThread = new ClientServerThread(ipAddress, port, this.getPk());
			exec.execute(clientServerThread);
		//}
		exec.shutdown();
	}

	/**
	 * 功能描述:
	 *
	 * @author  lizhenbin
	 * <p>创建日期 :Apr 26, 2012 11:47:42 PM</p>
	 *
	 * @param args
	 *
	 * <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
	 */
	public static void main(String[] args) {
		
		ClientServer clientServer = new ClientServer();
		try {
			clientServer.initSocket();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

 这样就可以实现TCP之间通信了