服务端
import java.net.*; import java.io.*; public class TCPServerSocket { public static void main(String[] args) throws Exception{ String data = ""; //while (true) { try{ ServerSocket ss = new ServerSocket(8888); Socket s = ss.accept(); InputStream in = s.getInputStream(); int len = 0; byte[] buff = new byte[1024]; while((len = in.read(buff)) > 0) { data += new String(buff,0,len); } } catch (Exception e){ System.out.println("Exception"); } System.out.println(data); //} } }
客户端
import java.net.*; import java.io.*; public class TCPSocket{ public static void main(String[] args) throws Exception{ int port = 8888; String ip = "127.0.0.1"; //InetAddress address = InetAddress.getByAddress(stringToByte(ip)); InetAddress address = InetAddress.getByName("localhost"); Socket socket = new Socket(address, port); OutputStream out = socket.getOutputStream(); String data = "hello"; byte buff[] = data.getBytes(); out.write(buff,0,buff.length); out.flush(); socket.close(); } public static byte[] stringToByte (String ip){ String[] strArr = ip.split("."); byte[] IPArr = new byte[4]; System.out.println(strArr.length); for(int i = 0; i < 4; i++){ IPArr[i] = (byte)Integer.parseInt(strArr[i]); } return IPArr; } }
本文出自 “生命不息,折腾不止” 博客,请务必保留此出处http://admxj.blog.51cto.com/10955090/1741400
原文地址:http://admxj.blog.51cto.com/10955090/1741400