java网络编程 -学习篇(2)一对多聊天通讯程序

//客户端
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class FileClient {
	public static void main(String[] args) {
		Socket server=new Socket();
		try {
			String inputString;
			server=new Socket("localhost",8888);
			System.out.println("请输入信息:");
			BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
			PrintWriter os=new PrintWriter(server.getOutputStream());
			BufferedReader is=new BufferedReader(new InputStreamReader(server.getInputStream()));
			inputString=sin.readLine();
			while(inputString!=null&&!inputString.trim().equals("quit")) {
				os.println(inputString);
				os.flush();
				System.out.println("Client发送的消息为:"+inputString);
				System.out.println("Server发送的消息为"+is.readLine());
				inputString=sin.readLine();
			}
			os.close();
			is.close();
			server.close();
			System.out.println("聊天结束!");
		}catch(UnknownHostException e) {
			e.printStackTrace();
			}
			catch(Exception e) {
			e.printStackTrace();
		}
	}
	}
//服务端
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class FileServer {
public static void main(String[] args) {
    try {
        ServerSocket server=null;
        try {
          server=new ServerSocket(8888);
            }catch(Exception e)
        {
                System.out.println("Error:"+e);
                System.exit(-1);
        }
        Socket client=null;
        try {
            client=server.accept();
        }catch(Exception e) {
            System.out.println("接受请求失败");
            System.exit(-1);
        }
        String inputString;
        BufferedReader is=new BufferedReader(new InputStreamReader(client.getInputStream()));
        PrintWriter os=new PrintWriter(client.getOutputStream());
        BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Client发送的信息为:"+is.readLine());
        inputString =sin.readLine();
        while(inputString!=null&&!inputString.trim().equals("quit")) {
            os.println(inputString);
            os.flush();
            System.out.println("Server发送的消息为:"+inputString);
            System.out.println("Client发送的消息为"+is.readLine());
            inputString=sin.readLine();
        }
        os.close();
        is.close();
        client.close();
        server.close();
        server.close();
        System.out.println("聊天结束!");
    }catch(Exception e) {
        System.out.println("Error:"+e);
    }
}
}
//运行结果
 



你可能感兴趣的:(java)