Java开发实现的Socket双向通信功能示例
程序员文章站
2023-12-18 17:06:52
本文实例讲述了java开发实现的socket双向通信功能。分享给大家供大家参考,具体如下:
服务端
import java.io.bufferedreader;...
本文实例讲述了java开发实现的socket双向通信功能。分享给大家供大家参考,具体如下:
服务端
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相关内容感兴趣的读者可查看本站专题:《java socket编程技巧总结》、《java文件与目录操作技巧汇总》、《java数据结构与算法教程》、《java操作dom节点技巧总结》和《java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。