TCP

来源:互联网 发布:高中数学教学软件 编辑:程序博客网 时间:2024/06/05 04:45
package TCP;import java.io.InputStream;import java.net.InetAddress;import java.net.Socket;public class TCPClientTest {public static void main(String[] args) throws Exception {// TODO Auto-generated method stubnew TCPClient().connect();}}class TCPClient{private static final int PORT = 8002;public void connect() throws Exception{Socket client = new Socket(InetAddress.getLocalHost(),PORT);InputStream is = client.getInputStream();byte[] buf = new byte[1024];int len = is.read(buf);System.out.println(new String(buf,0,len));client.close();}}
package TCP;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class TCPServerTest {public static void main(String[] args) throws Exception  {new TCPServer().listen();}}class TCPServer{private static final int PORT = 8002;public void listen() throws Exception{ServerSocket serverSocket = new ServerSocket(PORT);Socket client = serverSocket.accept();OutputStream os = client.getOutputStream();System.out.println("开始与客户端交互数据");os.write(("Hello World!").getBytes());Thread.sleep(5000);System.out.println("结束与客户端交互数据");os.close();client.close();}}



原创粉丝点击