首页 > 代码库 > java之TCP(Socket,serverSocket)实例
java之TCP(Socket,serverSocket)实例
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!"); } }
java之TCP(Socket,serverSocket)实例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。