客户端的代码:
package tcp.http; import java.io.*; import java.net.*; import java.util.Scanner; public class Client{ public static void main(String[] args) throws IOException{ Scanner scanner=new Scanner(System.in); //1.创建Socket Socket tcpClientSocket=new Socket(); //2.TCP要发送消息,必须先建立连接 byte[] IPv4={127,0,0,1}; //连接到本机 InetAddress serverAddress=InetAddress.getByAddress(IPv4); SocketAddress serverSocketAddress=new InetSocketAddress(serverAddress,7777); tcpClientSocket.connect(serverSocketAddress);//连接上了,(连接过程代码比较长,但是没有什么复杂的,只需要查文档根据函数的构造过程,一步步来写就好了) while(true){ //写个死循环来聊天 String request=scanner.nextLine(); //通过字节流写入请求 OutputStream os=tcpClientSocket.getOutputStream(); //通过打印流打印和写入 PrintStream out=new PrintStream(os,true,"UTF-8"); out.println(request); //通过字节流读取响应 InputStream is=tcpClientSocket.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8")); //通过readLine()来保证每次都能把一句完整的话读完(\r\n是标志); String respOnse=reader.readLine(); System.out.println(" "+response); } //tcpClientSocket.close(); } }
服务器端的代码:
package tcp.threads; import java.io.*; import java.net.*; import java.util.Scanner; import java.util.concurrent.*; public class Server{ private static class TalkRunnable implements Runnable{ //一个个的工作线程 private Socket clientSocket; TalkRunnable(Socket socket){ this.clientSocket=socket; } @Override public void run(){ try{ InetAddress clientAddress=clientSocket.getInetAddress(); int clientPort=clientSocket.getPort(); System.out.printf("ID为 %s:%d 的好友上线了%n",clientAddress.getHostAddress(),clientPort); //获取字节流 InputStream is=null; is=clientSocket.getInputStream(); //字节流转换为字符流 InputStreamReader isReader=null; isReader=new InputStreamReader(is,"UTF-8"); //获取输出字节流 OutputStream os=clientSocket.getOutputStream(); //获取打印流 PrintStream out=new PrintStream(os,true,"UTF-8"); //获取缓冲字符流 BufferedReader reader=new BufferedReader(isReader); while(true){ //死循环聊天 String line=reader.readLine(); System.out.println(" 好友说:"+line); Scanner scanner=new Scanner(System.in); String respOnse=scanner.nextLine(); out.println(response); } }catch(IOException e){ e.printStackTrace(); } } } public static void main(String[] args) throws IOException{ //监听连接 ServerSocket tcpServerSocket=new ServerSocket(7777); //定义阻塞队列 BlockingQueuequeue=new LinkedBlockingQueue<>(); //创建线程池 ExecutorService pool=new ThreadPoolExecutor(100,100,0,TimeUnit.MILLISECONDS,queue); while(true){ //TCP 要发送消息必须先建立连接 Socket clientSocket=tcpServerSocket.accept(); pool.execute(new TalkRunnable(clientSocket));//有一个客户端连接到服务器,就起一个线程来专门处理这个对话 } } }
运行结果:
为什么要使用多线程?
因为单线程会发生阻塞,聊天就进行不下去了。。。
又是自己和自己聊天的一天= =,最近好迷TCP和UDP,欢迎各位大佬批评指正呀,一起交流呀!!! 啦啦啦
对比这个聊天程序和上一篇用UDP写的聊天程序可以更好的体会TCP和UDP的区别。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。