TCP网络编程 双向单次通讯
客户机端
package tcp; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class TcpClient { 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()); //获取到输入流对象,读取服务器回送的数据 InputStream inputStream = s.getInputStream(); byte buf [] = new byte[1024]; int length = inputStream.read(buf); System.out.println(new String(buf, 0, length)); s.close(); } }
服务器端
package tcp; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * * @author xiaotao *客户端发送一个字符串,并接受服务器端回传的消息 */ public class TcpServer { 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)); //获取socket输出流对象,向客户端发送数据 OutputStream outputStream = socket.getOutputStream(); outputStream.write("收到你发的消息,客户端你好".getBytes()); serverSocket.close(); } }