zoukankan      html  css  js  c++  java
  • Tcp协议创建一个客户端和服务端(提供聊天)

    //客户端
    package tcpdemo;
    
    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;
    
    public class StringSendDemo {
    
    	public static void main(String[] args) throws UnknownHostException, IOException {
    		// TODO Auto-generated method stub
    		Socket s = new Socket("192.168.2.143",10003);
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		PrintWriter out = new PrintWriter(s.getOutputStream(),true);
    		BufferedReader bfrin =  new BufferedReader(new InputStreamReader(s.getInputStream()));
    		
    		String line = null;
    		
    		byte buf[] = new byte[1024];
    		while((line = br.readLine()) != null)
    		{
    			if(line.equals("over"))break;
    			out.println(line);
    			
    			String string = bfrin.readLine();
    			System.out.println(string);
    		}
    		
    		s.close();
    		br.close();
    		bfrin.close();
    		out.close();
    
    	}
    
    }
    
    //服务端
    
    package tcpdemo;
    
    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;
    
    public class StringServerDemo {
    
    	public static void main(String[] args) throws IOException {
    		// TODO Auto-generated method stub
    		ServerSocket ss = new ServerSocket(10003);
    		
    		Socket s = ss.accept();
    		BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream()));
    		byte buf[] = new byte[1024];
    		
    		String line = null;
    		PrintWriter os = new PrintWriter(s.getOutputStream(),true);
    		while((line = brin.readLine()) != null)
    		{
    			System.out.println(line);
    			os.println(line.toUpperCase());
    		}
    		
    		ss.close();
    		s.close();
    		brin.close();
    		os.close();
    	}
    
    }
    

      

  • 相关阅读:
    学习笔记65—学位和学历区别
    学习笔记64—兴趣阅读之文学
    学习笔记63—兴趣阅读之法律
    学习笔记62—兴趣阅读之管理学
    学习笔记61—兴趣阅读之经济学
    学习笔记60—SPSS
    学习笔记59—收藏这7个在线配色神器,再也不愁配色灵感了
    学习笔记58—3D杯子设计
    网络处理2-异步POST请求和同步请求
    网络处理1-异步GET请求
  • 原文地址:https://www.cnblogs.com/WINDZLY/p/11923817.html
Copyright © 2011-2022 走看看