网络通信 Socket 实现TCP

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Mr_Leixiansheng/article/details/78217565

转载请注明出处:https://blog.csdn.net/mr_leixiansheng/article/details/78217565


实现步骤:

server

1)创建服务器端Socket,及ServerSocket,指定绑定的端口,并监听此端口

2)调用accept()开始监听

3)获取输入流,读取客户端信息

4)获取输出流,响应客户端的求情

5)关闭资源

client

1)创建客户端Socket,指定服务器地址和端口

2)获取输出流,向服务器发送消息

3)获取输入流,读取服务器消息

4)关闭资源


代码如下

server

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.ServerSocket;
import java.net.Socket;

/**
 * 
 * @author leixiansheng
 *基于TCP的Socket通信
 *服务器端
 *完成输入或输出流之后必须关闭 ( socket.shutdownInput() 
 *或socket.shutdownInput()  )让下一个流进来
 */
public class Server {
	
	public static void main(String[] args) {
		try {
			//1、创建服务器端Socket,及ServerSocket,指定绑定的端口,并监听此端口
			ServerSocket serverSocket = new ServerSocket(8888);//端口号建议在1023之后
			
			//2、调用accept()开始监听,等待客户端的连接(阻塞在此)
			System.out.println("***服务器即将启动,等待客户端连接***");
			Socket socket = serverSocket.accept();
			
			//3、获取输入流,读取客户端信息
			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr); //提高读取效率
			
			String content = null;
			while((content=br.readLine())!=null){
				System.out.println("我是服务器,读取的客户端内容是:"+content);
			}
			socket.shutdownInput(); //关闭输入流
			
			//4、获取输出流,响应客户端的求情
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			pw.write("欢迎登录");
			pw.flush(); //输出缓存内容
			
			//5、关闭资源
			pw.close();
			os.close();
			br.close();
			isr.close();
			is.close();
			socket.close();
			serverSocket.close();
			
			//服务器多线程处理 :多个客户端连接同一个服务器
//			socketThread(serverSocket); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
				
	}

	/**
	 * 服务器多线程测试(需要将步骤 2、3、4、5注解掉)
	 */
	private static void socketThread(ServerSocket serverSocket) {
		System.out.println("***服务器即将启动,等待客户端连接***");
		int num = 0;
		while(true){
			try {
				Socket socket = serverSocket.accept();
				ServerThread serverThread = new ServerThread(socket);
				serverThread.run();
				num++;
				System.out.println("客户端连接数量(次数):"+num);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

client

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.net.UnknownHostException;

/**
 * 
 * @author leixiansheng
 *客户端
 *完成输入或输出流之后必须关闭 ( socket.shutdownInput() 
 *或socket.shutdownInput()  )让下一个流进来
 */
public class Client {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			//1、创建客户端Socket,指定服务器地址和端口
			Socket socket = new Socket("localhost", 8888);
			
			//2、获取输出流,向服务器发送消息
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			pw.write("用户名:admin;密码:123");
			pw.flush(); //将pw缓存输出
			socket.shutdownOutput(); //关闭输出流
			
			//3、获取输入流
			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr); //提高读取效率
			
			String content = null;
			while((content=br.readLine())!=null){
				System.out.println("我是客户端,读取的服务器内容是:"+content);
			}
			
			//4、关闭资源
			br.close();
			isr.close();
			is.close();
			pw.close();
			os.close();
			socket.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
ServerThread(服务器多线程)

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;


public class ServerThread implements Runnable {

	private Socket socket;
	
	public ServerThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		InputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		OutputStream os = null;
		PrintWriter pw = null;
		
		try {
			//3、获取输入流,读取客户端信息
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr); //提高读取效率
			
			String content = null;
			while((content=br.readLine())!=null){
				System.out.println("我是服务器,读取的客户端内容是:"+content);
			}
			socket.shutdownInput(); //关闭输入流
			
			//4、获取输出流,响应客户端的求情
			os = socket.getOutputStream();
			pw = new PrintWriter(os);
			pw.write("欢迎登录");
			pw.flush(); //输出缓存内容
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			//5、关闭资源
			try {
				if(pw!=null){
					pw.close();
				}
				if(os!=null){
					os.close();
				}
				if(br!=null){
					br.close();
				}
				if(isr!=null){
					isr.close();
				}
				if(is!=null){
					is.close();
				}
				if(socket!=null){
					socket.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}



展开阅读全文

没有更多推荐了,返回首页