java模拟聊天

package randomAccessFile;

import java.io.IOException;
import java.io.PipedReader;

//消息接收端
class Receive
{
	static PipedReader pr;
	static Send s;
	public Receive() {
		
	}
	public Receive(Send s)
	{
		this.s=s;
	}
	public Receive(PipedReader pr,Send s)
	{
		super();
		this.pr = pr;
		this.s=s;
	}
	public static String recevie() throws IOException//接收消息
	{
		String l="";
		char ch='\0';
		while((ch=(char)pr.read())!='?')
		{
			l+=ch;
		}
		int length=Integer.parseInt(l);
		char [] message=new char[length];
		pr.read(message);
		if(pr!=null)
		{
		// pr.close();
		}
		String m=new String(message);
		System.out.println("收到消息:"+m);
		if(m.equals("88"))
		{
			System.out.println("聊天结束!");
			//关闭流
			System.exit(0);
		}
		//继续通知发送
		else
		{
		  s.send();
		 
		}
		return m;
	}
	
}

 

package randomAccessFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedWriter;

//消息发送端
class Send 
{
	PipedWriter pw;
    Receive rec;
    public Send(PipedWriter pw)
    {
    	this.pw=pw;
    }
	public Send(PipedWriter pw,Receive rec)
	{
		super();
		this.pw = pw;
		this.rec=rec;
		
	}
	public void send() throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String message="";
		String messageTest="";
		do
		{
			System.out.println("请输入你要发的消息:");
			message=br.readLine();
			messageTest=message.trim();//去掉左边空格
			if(messageTest.length()==0)
			{
				System.out.println("不能发送空消息");
			}
			
		}
		while(messageTest.equals(""));
		System.out.println("你发送的内容是:"+message);
		pw.write(message.length()+"?"+message);
		//通知接收
		rec=new Receive();
		rec.recevie();
		
	}

}

 

package randomAccessFile;
import java.io.*;
public class Test
{
	public static void main(String[] args) throws IOException 
	{
		
		PipedWriter pw=new PipedWriter();
		PipedReader pr=new PipedReader();
		Send s=new Send(pw);
		Receive r=new Receive(pr,s);
		pr.connect(pw);
		boolean a=true;
		try
		{
			while(a)
			{
			 s.send();
			 r.recevie();
			}
		} 
		catch (IOException e)
		{			
			e.printStackTrace();
		}
			if(pw!=null)
			{
				pw=null;
			}
			if(pr!=null)
			{
				pr=null;
			}
		
	
	}
}

 

你可能感兴趣的:(java)