Tcp网络编程 双向多次通讯
Posted xiaotao520
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Tcp网络编程 双向多次通讯相关的知识,希望对你有一定的参考价值。
客户端
package tcptx; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class TcpClient { public static void main(String[] args) throws UnknownHostException, IOException { //建立TCP的服务 Socket s = new Socket(InetAddress.getLocalHost(), 9000); //获取Socket的输出流 OutputStreamWriter sockOut = new OutputStreamWriter(s.getOutputStream()); //获取键盘的输入流对象,读取数据 BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in)); String line = null; //不断读取键盘数据 while((line = keyReader.readLine())!=null) { sockOut.write(line+"\r\n");//需要断行 sockOut.flush(); System.out.println("客户端数据已发出。。。"); } //关闭资源 s.close(); } }
服务端
package tcptx; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class TcpServer { public static void main(String[] args) throws IOException { //建立TCP的服务器,并监听一个端口 ServerSocket serverSocket = new ServerSocket(9000); //接受客户端的连接 Socket socket = serverSocket.accept(); //获取输入流对象,读取客户端发送的内容 BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); //读取客户端数据 String line = null; while((line = socketReader.readLine())!=null) { System.out.println("数据接收中>>>>>>>>>>>"); System.out.println(line); } //关闭资源 serverSocket.close(); } }
以上是关于Tcp网络编程 双向多次通讯的主要内容,如果未能解决你的问题,请参考以下文章