Java网络编程(TCP协议-服务端和客户端交互)
Posted 菜鸟奋斗史
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java网络编程(TCP协议-服务端和客户端交互)相关的知识,希望对你有一定的参考价值。
客户端:
1 package WebProgramingDemo; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.net.Socket; 7 import java.net.UnknownHostException; 8 9 public class SocketDemo { 10 11 /** 12 * @param args 13 * @throws IOException 14 * @throws UnknownHostException 15 */ 16 public static void main(String[] args) throws IOException { 17 18 Socket s=new Socket("192.168.2.103",10002); 19 OutputStream out=s.getOutputStream(); 20 out.write("Java".getBytes()); 21 InputStream is=s.getInputStream(); 22 byte buf[]=new byte[1024]; 23 int len=is.read(buf); 24 System.out.println(new String(buf,0,len)); 25 s.close(); 26 } 27 28 }
服务端:
1 package WebProgramingDemo; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.net.ServerSocket; 7 import java.net.Socket; 8 9 public class ServerSocketDemo { 10 11 /** 12 * @param args 13 * @throws IOException 14 */ 15 public static void main(String[] args) throws IOException { 16 17 ServerSocket ss = new ServerSocket(10002); 18 Socket s = ss.accept(); 19 String ip = s.getInetAddress().getHostAddress(); 20 System.out.println(ip + "....connected...."); 21 InputStream in = s.getInputStream(); 22 int len = 0; 23 byte[] buf = new byte[1024]; 24 len = in.read(buf); 25 System.out.println(new String(buf, 0, len)); 26 OutputStream os=s.getOutputStream(); 27 os.write("收到".getBytes()); 28 os.close(); 29 s.close(); 30 ss.close(); 31 } 32 33 }
以上是关于Java网络编程(TCP协议-服务端和客户端交互)的主要内容,如果未能解决你的问题,请参考以下文章
Java网络编程TCP程序,服务器和客户机交互流程以及基本操作步骤。