zoukankan      html  css  js  c++  java
  • 服务器 客户端 实现TCP 1--socket

    附上其他好的文章的链接 
    https://blog.csdn.net/wo541075754/article/details/66971888
    https://blog.csdn.net/u012561176/article/details/48183181
    https://blog.csdn.net/u010142437/article/details/18039961
    https://blog.csdn.net/alen0217/article/details/42558085
    https://blog.csdn.net/qq_34444097/article/details/78955511
         小笔记:~Thread t 的意思是声明线程t ,new Thread(this) 的意思是把当前的类实例化为一个线程
    该Thread对象调用start()方法后,会执行该对象重写的run()方法,结果也就是Run of Thread,输出完后,run()方法返回,该线程对象的生命周期也就结束了。从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。
         finalize方法是Object提供的的实例方法,使用规则如下:当对象不再被任何对象引用时,GC会调用该对象的finalize()方法 finalize()是Object的方法,子类可以覆盖这个方法来做一些系统资源的释放或者数据的清理,可以在finalize()让这个对象再次被引用,避免被GC回收;但是最常用的目的还是做cleanup,Java不保证这个finalize()一定被执行;但是保证调用finalize的线程没有持有任何user-visible同步锁。在finalize里面抛出的异常会被忽略,同时方法终止。当finalize被调用之后,JVM会再一次检测这个对象是否能被存活的线程访问得到,如果不是,则清除该对象。也就是finalize只能被调用一次;也就是说,覆盖了finalize方法的对象需要经过两个GC周期才能被清除。
    https://www.cnblogs.com/alsf/p/6852852.html 传到服务器需要用printstream流进行
    下面实现客户端 服务器的通信
    服务器代码

    import java.io.*;
    import java.net.*;
    //点对点连接
    public class Server {
    	// 太久没操作会自动停
    	public static void main(String[] args) throws IOException {
    		// 监听 并传递一个端口
    		ServerSocket server = new ServerSocket(2010);// 默认自己ip的地址
    		System.out.println("服务器准备就绪");
    		// 持续收到消息
    		System.out.println("服务器的信息" + server.getLocalPort() + " " + server.getInetAddress());
    		// 客户端连接输出
    		// 开始接受 服务器不关闭 所以采用true
    		while (true) {
    			Socket client = server.accept();
    			// 持续接收 因为是服务器 所以 不仅仅接受一个
    			ClientHandler clientHandler = new ClientHandler(client);
    			clientHandler.start();
    		      }
    	     }
    	private static class ClientHandler extends Thread {
    		private Socket socket;
    		// 持续接受
    		private boolean flag = true;
    		// socket 是 连接到服务器上
    		ClientHandler(Socket socket) {
    			this.socket = socket;
    		}
    		public void run() {
    			// 连接成功后 正式运行前先输出客户端的信息
    			System.out.println("与" + socket.getLocalAddress() + "连接成功" + "," + socket.getPort());
    			try {
    				// 接受输入
    				PrintStream output = new PrintStream(socket.getOutputStream());
    				BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    				do {
    					String str = input.readLine();
    					if (str.equalsIgnoreCase("bye")) {
    						flag = false;
    						System.out.println("跟" + socket.getInetAddress() + "断开连接");
    					} 
    					else {
    						System.out.println(str);
    						//如果没有回送的话会报错
    						output.println("回送:"+str.length());
    					}
    				}while(flag);
     
    			} catch (Exception e) {
    				System.out.println(e);
    				System.out.println("连接异常");
    			}
    			try {
    				socket.close();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    	}
    

    客户端

    import java.io.*;
    import java.net.*;
    public class Client {
    	public static void main(String[] args) throws UnknownHostException, IOException {
    		Socket socket = new Socket();
    		socket.setSoTimeout(3000);// 超时时间
    		// 下面要先运行服务器 不然连接不了 要从服务器端开始建立连接
    		socket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 2010));
    		System.out.println("已建立连接");// 没建立连接会报错//InetAddress//输入地址
    		System.out.println("服务器的主机名+ip地址" + socket.getInetAddress());
    		System.out.println("客户端的端口" + socket.getPort());// 2000
    		try {
    			todo(socket);
    		} // 捕捉异常 任何异常
    		catch (Exception e) {
    			System.out.println("异常关闭");
    		}
    		socket.close();
    		System.out.println("客户端已退出");
    	}
    	// 发送接受
    	private static void todo(Socket client) throws IOException {
    		// 键盘输入流
    		InputStream in = System.in;
    		BufferedReader input = new BufferedReader(new InputStreamReader(in));
    		// 得到输出流,并打印
    		OutputStream  out = client.getOutputStream();
    		PrintStream outprint = new PrintStream(out);
    		//得到对方的发过来的消息
    		InputStream inputstream = client.getInputStream();
    		BufferedReader inputstreamreader = new BufferedReader(new InputStreamReader(inputstream));
    		boolean flag = true;
    		while(flag) {
    		//键盘读取一行
    		String str = input.readLine();
    		//发送到对方采用的时printStream
    		outprint.println(str);
    		//读取服务器的消息一行。而还没有
    		String s =inputstreamreader.readLine();
    		if(s.equalsIgnoreCase("bye")) {	
    			System.out.println("跟"+client.getInetAddress()+"断开连接");
    			flag = false;
    		}
    		else//服务器输过来的消息 打印出来
    			System.out.println(s);
    	}
    		outprint.close();
    		inputstreamreader.close();
    }
    }
    

    简洁个人版
    服务器

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class Server {
    	public static void main(String[] args) throws IOException {
    		ServerSocket server = new ServerSocket(5050);
    		while (true) {
    			Socket client = server.accept();
    			System.out.println(client.getPort() + "已上线");
    			clientserver c = new clientserver(client);
    			c.start();
    		}
    	}
    }
    class clientserver extends Thread {
    	Socket client;
    	clientserver(Socket socket) {
    		this.client = socket;
    	}
    	public void run() {
    		System.out.println("与" + client.getInetAddress() + "连接成功");
    		try {
    			BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
    			PrintStream print = new PrintStream(client.getOutputStream());
    			boolean flag = true;
    			while (flag) {
    				String s = input.readLine();
    				if (s.equals("bye")) {
    					flag = false;
    				} else {
    					System.out.println(s);
    					print.println("已发送");
    				}
    			}
    		} catch (Exception e) {
    			System.out.println("连接异常" + client.getPort() + "已下线");
    		}
    	}
    }
    

    客户端

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.Socket;
    import java.util.Scanner;
    public class Client {
    	public static void main(String[] args) {
    		try {
    			Socket socket = new Socket("localhost", 5050);
    			System.out.println("与"+socket.getInetAddress()+"连接成功");
    			try {
    				BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    				PrintStream print = new PrintStream(socket.getOutputStream());
    				Scanner scanner = new Scanner(System.in);
    				while (true) {
    					String send = scanner.nextLine();
    					print.println(send);
    					String str = input.readLine();
    					System.out.println(str);
    				}
    			} finally {
    				socket.close();
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    
  • 相关阅读:
    监听器heMQ组合的入门练习
    错误积累
    测试cxf 客户端
    day18-1-17获取界面参数
    Station 项目注意事项
    cxf_spring的结合
    ws_cxf入门 错误
    Oracle游标
    Oracle存储函数,存储过程
    Oracle查询
  • 原文地址:https://www.cnblogs.com/cznczai/p/11148110.html
Copyright © 2011-2022 走看看