团队项目是建立局域网聊天室,我们打算用socket通信实现消息传递。考虑网络方面java有很多封装好的类库,使用十分方便,我们团队初步打算使用java实现。
目前我和王以正同学完成代码。目前我起了一个头,完成了客户端内核的基本框架。代码如下:
1 public class Client { 2 3 Socket soc = null; 4 public String name; 5 public String roomName; 6 public InputStream is = null; 7 public OutputStream os = null; 8 public BufferedReader br = null; 9 public BufferedWriter bw = null; 10 public BufferedReader sysbr = null; 11 12 public String getName() { 13 return name; 14 } 15 16 public void setName(String name) { 17 this.name = name; 18 } 19 20 public String getRoomName() { 21 return roomName; 22 } 23 24 public void setRoomName(String roomName) { 25 this.roomName = roomName; 26 } 27 28 public Client(String name) { 29 // TODO Auto-generated constructor stub 30 this.name = name; 31 try { 32 soc = new Socket("localhost", 5555); 33 is = soc.getInputStream(); 34 os = soc.getOutputStream(); 35 System.out.println(soc.getInetAddress()+" "); 36 System.out.println(soc.getPort()); 37 br = new BufferedReader(new InputStreamReader(is)); 38 bw = new BufferedWriter(new OutputStreamWriter(os)); 39 sysbr = new BufferedReader(new InputStreamReader(System.in)); 40 41 } catch (IOException e) { 42 // TODO Auto-generated catch block 43 e.printStackTrace(); 44 } 45 } 46 47 public static void main(String[] args) { 48 // TODO Auto-generated method stub 49 Client c = new Client("he"); 50 String msg; 51 try { 52 do { 53 msg = c.sysbr.readLine(); 54 c.bw.write(msg + " "); 55 c.bw.flush(); 56 if((msg=c.br.readLine()) != null){ 57 System.out.println(c.br); 58 } 59 } while (!msg.equals("quit")); 60 System.out.println("对话结束"); 61 62 } catch (IOException e) { 63 // TODO Auto-generated catch block 64 e.printStackTrace(); 65 } 66 67 } 68 69 }
其中每个客户类包含成员变量:昵称(name)、所属聊天室名称(roomName)等。能建立到服务器的连接,将在建立好服务器端后与服务器端一起完善功能。