怎么在Java中利用Socket实现双向通信
本篇文章为大家展示了怎么在Java中利用Socket实现双向通信,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
创新互联建站主要从事网站建设、成都做网站、网页设计、企业做网站、公司建网站等业务。立足成都服务麻山,十年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575
服务端
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Server_1 { public static void main(String[] args) { InputStreamReader isr; BufferedReader br; OutputStreamWriter osw; BufferedWriter bw; String str; Scanner in = new Scanner(System.in); try { ServerSocket server = new ServerSocket(4444);// 在本机的4444端口开放Server Socket socket = server.accept();// 只要产生连接,socket便可以代表所连接的那个物体,同时这个server.accept()只有产生了连接才会进行下一步操作。 System.out.println(socket.getInetAddress());// 输出连接者的IP。 System.out.println("建立了一个连接!"); while (true) { isr = new InputStreamReader(socket.getInputStream()); br = new BufferedReader(isr); System.out.println(socket.getInetAddress() + ":" + br.readLine()); osw = new OutputStreamWriter(socket.getOutputStream()); bw = new BufferedWriter(osw); System.out.print("回复:"); str = in.nextLine(); bw.write(str + "\n"); bw.flush(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
客服端
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Client_1 { public static void main(String[] args) { InputStreamReader isr; BufferedReader br; OutputStreamWriter osw; BufferedWriter bw; String str; Scanner in = new Scanner(System.in); try { Socket socket = new Socket("localhost", 4444); // System.out.println(socket.getInetAddress());// 输出连接者的IP。 System.out.println("成功连接服务器"); while (true) { osw = new OutputStreamWriter(socket.getOutputStream()); bw = new BufferedWriter(osw); System.out.print("回复:"); str = in.nextLine(); bw.write(str + "\n"); bw.flush(); isr = new InputStreamReader(socket.getInputStream()); br = new BufferedReader(isr); System.out.println(socket.getInetAddress() + ":" + br.readLine()); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
上述内容就是怎么在Java中利用Socket实现双向通信,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。
本文题目:怎么在Java中利用Socket实现双向通信
标题链接:http://azwzsj.com/article/piseii.html