1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import java.io.*; import java.net.*;
public class TcpClient { public static void main(String[] args) { String hostname = "localhost"; int port = 12345;
try (Socket socket = new Socket(hostname, port)) {
OutputStream output = socket.getOutputStream(); PrintWriter writer = new PrintWriter(output, true);
InputStream input = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input));
writer.println("我们都已经成功了");
String response = reader.readLine(); System.out.println("接收到服务端返回的消息: " + response);
} catch (UnknownHostException ex) { System.out.println("66666Server not found: " + ex.getMessage()); } catch (IOException ex) { System.out.println("7777I/O error: " + ex.getMessage()); } } }
|