import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import org.junit.Test; public class TestTCP { @Test public void rend() throws UnknownHostException, IOException{ Socket socket = new Socket("127.0.0.1",9999); int i = (int) (Math.random()*1000); String strMessage = "send:"+i; System.out.println(strMessage); socket.getOutputStream().write(strMessage.getBytes()); socket.shutdownOutput(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(socket.getInputStream())); String str = buffRead.readLine(); System.out.println(str); buffRead.close(); socket.close(); System.out.println("socket.close()"); } @Test public void revice() throws IOException{ ServerSocket serverSocket = new ServerSocket(9999); boolean flag = true; BufferedReader buffRead = null; Socket socket = null; while(flag){ socket = serverSocket.accept(); buffRead = new BufferedReader(new InputStreamReader(socket.getInputStream())); String str = buffRead.readLine(); System.out.println(str); socket.shutdownInput(); socket.getOutputStream().write(("revice:"+str).getBytes()); socket.close(); System.out.println("socket.close()"); } buffRead.close(); serverSocket.close(); System.out.println("serverSocket close!"); } }
时间: 2024-10-18 06:47:21