TCP简单程序
服务器段:
package com.dcz.socket; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class TcpServer { public static void main(String[] args) { String data = "你好啊,socket 世界!"; // 端口 int port = 17001; ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); System.out.println("服务端已经准备就绪......"); boolean isAccept = true; while (isAccept) { Socket client = serverSocket.accept(); InetAddress inetAddress = client.getInetAddress(); System.out.println("客户端ip:" + inetAddress); OutputStream clientOutputStream = client.getOutputStream(); clientOutputStream.write(data.getBytes()); clientOutputStream.close(); } serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
客户端代码:
package com.dcz.socket; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.UnknownHostException; import org.apache.commons.io.output.ByteArrayOutputStream; public class TcpClient { public static void main(String[] args) { String address = "127.0.0.1"; int port = 17001; Socket client = null; try { client = new Socket(address, port); InputStream serverInputStream = client.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while((serverInputStream.read(buffer, 0, buffer.length)) != -1){ byteArrayOutputStream.write(buffer, 0, buffer.length); } byte[] data = byteArrayOutputStream.toByteArray(); System.out.println(new String(data, "utf-8")); byteArrayOutputStream.close(); client.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }