Java Socket 连接 Client端 和 Server端

9/6/2015来源:Java教程人气:2538

java Socket 连接 Client端 和 Server端

Client端:

importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.InetAddress;importjava.net.Socket;importjava.net.UnknownHostException;importjava.util.Scanner;publicclassChatClient{PRivatestaticfinalStringSERVER_ip="127.0.0.1";privatestaticfinalintSERVER_PORT=8888;Socketsocket=null;DataOutputStreamdos=null;DataInputStreamdis=null;privatebooleanbConnected=false;privatestaticScannerin=newScanner(System.in);privatestaticStrinGhostInfo=null;ThreadtRecv=newThread(newRecvThread());publicstaticvoidmain(String[]args){newChatClient().launch();}publicvoidlaunch(){connect();tRecv.start();}publicvoidconnect(){try{socket=newSocket(SERVER_IP,SERVER_PORT);dos=newDataOutputStream(socket.getOutputStream());dis=newDataInputStream(socket.getInputStream());bConnected=true;InetAddressaddr=InetAddress.getLocalHost();Stringip=addr.getHostAddress().toString();//获得本机IPStringaddress=addr.getHostName().toString();//获得本机名称hostInfo=ip+"\t"+address+"\tconnected.";System.out.println(hostInfo);dos.writeUTF(hostInfo);dos.flush();}catch(UnknownHostExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}publicvoiddisconnect()throwsIOException{try{dos.close();dis.close();socket.close();}catch(IOExceptione){}}privateclassRecvThreadimplementsRunnable{publicvoidrun(){while(bConnected){try{if(in.hasNext()){Stringtalk=in.nextLine();if(talk.equals("quit")){disconnect();bConnected=false;break;}dos.writeUTF(talk);dos.flush();}Stringtalk=dis.readUTF();System.out.println(talk);}catch(IOExceptione){e.printStackTrace();}}}}}

server端:

importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.EOFException;importjava.io.IOException;importjava.net.BindException;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.ArrayList;importjava.util.List;publicclassChatServer{booleanstarted=false;ServerSocketss=null;List<Client>clients=newArrayList<Client>();publicstaticvoidmain(String[]args){newChatServer().start();}publicvoidstart(){try{ss=newServerSocket(8888);started=true;}catch(BindExceptione){System.err.println("portinuse.pleasestopprogramusingthisportandrestart.");System.exit(0);}catch(IOExceptione){e.printStackTrace();}try{while(started){Sockets=ss.accept();Clientc=newClient(s);//System.out.println("aclientconnected.");newThread(c).start();clients.add(c);}}catch(IOExceptione){e.printStackTrace();}finally{try{ss.close();}catch(IOExceptione){e.printStackTrace();}}}classClientimplementsRunnable{privateSockets;privateDataInputStreamdis=null;privateDataOutputStreamdos=null;privatebooleanbConnected=false;publicClient(Sockets){this.s=s;try{dis=newDataInputStream(s.getInputStream());dos=newDataOutputStream(s.getOutputStream());bConnected=true;}catch(IOExceptione){e.printStackTrace();}}publicvoidsend(Stringstr){try{dos.writeUTF(str);dos.flush();}catch(IOExceptione){clients.remove(this);System.out.println("aclientquit.");//e.printStackTrace();}}publicvoidrun(){try{while(bConnected){Stringstr=dis.readUTF();solveTalk(str);}}catch(EOFExceptione){System.out.println("Clientclosed!");}catch(IOExceptione){e.printStackTrace();}finally{try{if(dis!=null)dis.close();if(dos!=null)dos.close();if(s!=null){s.close();s=null;}}catch(IOExceptione1){e1.printStackTrace();}}}privatevoidsolveTalk(Stringtalk){System.out.println(talk);for(inti=0;i<clients.size();i++){Clientc=clients.get(i);c.send(talk);}}}}