Tcp网络编程 单向通讯
package www; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; //客户机端,向服务器发送一串字符串 public class TestTcpC { public static void main(String[] args) throws UnknownHostException, IOException { //建立TCp的服务 Socket s = new Socket(InetAddress.getLocalHost(),9000); //获取到Socket的输出流 OutputStream outputStream = s.getOutputStream(); //利用输出流对象把数据写出 outputStream.write("服务器端,你好".getBytes()); s.close(); } }
package com.oracle.www; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; //服务器端,接受客户机发送的消息并输出 public class TestTcpS { public static void main(String[] args) throws IOException { //建立Tcp的服务端,并侦听一个端口 ServerSocket serverSocket = new ServerSocket(9000); //接受客户端的连接 Socket socket = serverSocket.accept(); //获取输入流对象,读取客户端发送的内容 InputStream inputStream = socket.getInputStream(); byte [] buf = new byte[1024]; int length = 0; length = inputStream.read(buf); System.out.println(new String(buf, 0, length)); //关闭资源 serverSocket.close(); socket.close(); inputStream.close(); } }