TCP编程
Posted 龘驫
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TCP编程相关的知识,希望对你有一定的参考价值。
Server.java
package com.zby; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { private static boolean running = true; public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(8888); System.out.println("LocalSocketAddress:" + serverSocket.getLocalSocketAddress()); System.out.println("----------------------------------------------------------"); while (running) { Socket socket = serverSocket.accept(); System.out.println("connected!"); System.out.println("RemoteSocketAddress:" + socket.getRemoteSocketAddress()); DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); String request = dataInputStream.readUTF(); System.out.println("request:" + request); String response = "Hello,Client!"; DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.writeUTF(response); System.out.println("response:" + response); System.out.println("disConnected!"); System.out.println(); socket.close(); } serverSocket.close(); } }
Client.java
package com.zby; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.InetAddress; import java.net.Socket; public class Client { public static void main(String[] args) throws Exception { Socket socket = new Socket(InetAddress.getLocalHost(), 8888, InetAddress.getLocalHost(), 7777); System.out.println("connected!"); System.out.println("LocalSocketAddress:" + socket.getLocalSocketAddress()); System.out.println("RemoteSocketAddress:" + socket.getRemoteSocketAddress()); System.out.println(); String request = "Hello,Server!"; DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.writeUTF(request); System.out.println("request:" + request); DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); String response = dataInputStream.readUTF(); System.out.println("response:" + response); System.out.println("disConnected!"); socket.close(); } }
以上是关于TCP编程的主要内容,如果未能解决你的问题,请参考以下文章