java之TCP(Socket,serverSocket)实例

Posted yutingliuyl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)实例的主要内容,如果未能解决你的问题,请参考以下文章

Java Socket编程之TCP

java之TCP(Socket,serverSocket)实例

java socket之传输实体类对象

Java网络编程之tcp的socket通信

网络编程之TCP-Socket

Java学习笔记之基于TCP协议的socket