本文实例讲述了java tcp通信客户端与端。分享给大家供大家参考,具体如下:
由服务器端发送数据
服务器端:
import java.io.*; import java.net.*; public class testsocket { public static void main(string[] args) { try { serversocket ss = new serversocket(8888); while(true) { socket s = ss.accept(); outputstream os = s.getoutputstream(); dataoutputstream dos = new dataoutputstream(os); dos.writeutf("hello" s.getinetaddress() "port" s.getport() "beybye"); dos.close(); // os.flush(); os.close(); // s.close(); } } catch (ioexception e) { e.printstacktrace(); system.out.println("there is a wrong"); } } }
用户端:
import java.io.*; import java.net.*; public class testclient { public static void main(string[] args){ try { socket s = new socket("127.0.0.1",8888); datainputstream dis = new datainputstream(s.getinputstream()); system.out.println(dis.readutf()); s.close(); dis.close(); } catch (exception e) { e.printstacktrace(); } } }
无论是客户端还是服务器端都可以收发数据。
交互型
用户端
import java.io.*; import java.net.*; public class testclient2 { public static void main(string[] args){ try { socket s = new socket("127.0.0.1",8886); dataoutputstream dos = new dataoutputstream(s.getoutputstream()); datainputstream dis = new datainputstream(s.getinputstream()); system.out.println(dis.readutf()); dos.writeutf("hey"); string str = null; if((str = dis.readutf()) != null) { system.out.println(str); } s.close(); dis.close(); dos.close(); } catch (exception e) { e.printstacktrace(); } } }
服务器端:
public class testserver2 { public static void main(string[] args) { inputstream in = null; outputstream out = null; try { serversocket ss = new serversocket(8886); while(true) { socket s = ss.accept(); in = s.getinputstream(); out = s.getoutputstream(); dataoutputstream dos = new dataoutputstream(s.getoutputstream()); datainputstream dis = new datainputstream(s.getinputstream()); string str = null; if((str = dis.readutf() )!= null) { system.out.println(str); system.out.println("form " s.getinetaddress()); system.out.println("port " s.getport()); // dos.writeutf("hello" s.getinetaddress() "port" s.getport() "beybye"); } dos.writeutf("hi hello"); dis.close(); dos.close(); s.close(); } } catch (ioexception e) { e.printstacktrace(); system.out.println("there is a wrong"); } } }