Java编写的基于Socket的聊天室程序

源代码在线查看: 用socket建立个最简单的聊天程序.txt

软件大小: 12 K
上传用户: atom0722
关键词: Socket Java 编写 程序
下载地址: 免注册下载 普通下载 VIP

相关代码

				/*用Socket建立个最简单的聊天程序
				
				Java、Socket、网络编程、聊天*/S
				
				/*一个作为Server*/
				import java.io.*;
				import java.net.*;
				public class MyServer{
				 public static void main(String[] args)
				      throws IOException{
				  ServerSocket s=new ServerSocket(8658);
				  System.out.println("开始:"+s);
				  try{
				   Socket socket=s.accept();
				   try{
				    System.out.println("连接接受"+socket);
				    BufferedReader in=new BufferedReader(new InputStreamReader
				      (socket.getInputStream()));
				    PrintWriter out=new PrintWriter(new BufferedWriter(
				     new OutputStreamWriter(socket.getOutputStream())),true);
				    while(true){
				     String str=in.readLine();
				     if(str.equals("q")) break;
				     System.out.println("对方说:"+str);
				     BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
				     String input=new String();
				     input=is.readLine().trim();
				     out.println(input);
				     System.out.print("我说:");
				     out.flush();
				    }
				   }
				   finally{
				    System.out.println("关闭....");
				    socket.close();
				   }
				  }
				  finally{
				   s.close();
				  }
				 }
				}
				
				/*一个作为Client*/
				import java.io.*;
				import java.net.*;
				public class MyClient{
				 public static void main(String[] args)
				   throws IOException{
				  InetAddress addr=InetAddress.getByName("127.0.0.1");
				  System.out.println("地址="+addr);
				  Socket socket=new Socket(addr,8658);
				  try{
				   System.out.println("socket="+socket);
				   BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
				    PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
				   for(;;){
				    System.out.print("我说:");
				    String input=new String();
				    input=is.readLine().trim();
				    out.println(input);
				    if(input.equals("q")) break;
				    BufferedReader in=new BufferedReader(new InputStreamReader
				        (socket.getInputStream()));
				     String str=in.readLine();
				    System.out.println("对方说:"+str);
				    out.flush();
				   }
				
				  }
				  finally{
				   System.out.println("关闭");
				   socket.close();
				  }
				 }
				}
							

相关资源