客户端服务器端实现双向通信

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class TcpServer 
{
	public static void main(String args[]) throws Exception
	{
		ServerSocket ss=new ServerSocket(5000);
		Socket socket=ss.accept();
		InputStream is=socket.getInputStream();
		byte[]by=new byte[1024];
		Thread.sleep((long)Math.random()*3000);
		int length=is.read(by);
		System.out.println(new String(by,0,length));
		//while(-1!=(is.read(by)))
		//{
			//System.out.println(new String(by));
		//}
		
		OutputStream os=socket.getOutputStream();
		byte[]b=new byte[1000];
		b="nice to meet you too!".getBytes();
		os.write(b);
		os.close();
		is.close();
		
	}
}
//这种双向通信必须要服务器首先开启监听模块,客户端进行连接通信,通信过程中输入输出的顺序给定后,不能更改

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;


public class TcpClient 
{
	public static void main(String args[]) throws Exception
	{
		Socket socket1=new Socket("localhost",5000);
		OutputStream os=socket1.getOutputStream();
		byte []b=new byte[1000];
		String str="hello,nice to meet you!";
		b=str.getBytes();
		os.write(b);
		InputStream is=socket1.getInputStream();
		byte []by=new byte[1024];
//		while(-1!=(is.read(by)))
//		{
//			System.out.println(new String(by));
//		}
		int length=is.read(by);
		System.out.println(new String(by,0,length));
		os.close();
		is.close();
		
	}
}

你可能感兴趣的:(java)