码迷,mamicode.com
首页 > 编程语言 > 详细

java之TCP(Socket,serverSocket)实例

时间:2017-08-06 20:38:55      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:div   int   null   str   test   .sh   track   mod   get   

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)实例

标签:div   int   null   str   test   .sh   track   mod   get   

原文地址:http://www.cnblogs.com/yutingliuyl/p/7295582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!