日期:2014-05-20  浏览次数:20753 次

简单的C/S聊天程序--请高手指教
import   java.net.*;
import   java.io.*;

public   class     SimpleCilent
{
public   static   void   main(String[]   args)  
{

Socket   cilent   =   null;
try
{
cilent   =   new   Socket( "192.168.0.14 ",8000);

if   (cilent   !=null   )
{

InputStream   s1   =   cilent.getInputStream();
OutputStream   s2   =   cilent.getOutputStream();

BufferedReader   input   =   new   BufferedReader(new   InputStreamReader(s1));
BufferedWriter   output   =   new   BufferedWriter(new   OutputStreamWriter(s2));

PrintWriter   print   =   new   PrintWriter(output);



BufferedReader   inputLine   =   new   BufferedReader(new   InputStreamReader(System.in));



while   (true)
{
System.out.println( "please   enter   content: ");
String   s   =   inputLine.readLine();

print.println(s);
print.flush();

if   (s.equals( "quit "))
{
break;
}
else
{
String   i_line   =   input.readLine();
System.out.println(i_line);
}
}

}

}
catch(Exception   e)
{
e.printStackTrace();
}

finally
{
try
{
if   (cilent   !=null   )
{
cilent.close();

}

}
catch(Exception   e1)
{
e1.printStackTrace();
}

}



}
}


import   java.net.*;
import   java.io.*;
public   class     SingleServer
{
public   static   void   main(String[]   args)  
{
ServerSocket   server   =   null;

int   singleNumber;

try
{
server   =   new   ServerSocket(8000);

Socket   form   =   server.accept();//此方法实现数据传输(客户端套接字)


if   (form   !=   null)
{

System.out.println( "start   .... "+form);

InputStream   s1   =   form.getInputStream();
OutputStream   s2   =   form.getOutputStream();

BufferedReader   input   =   new   BufferedReader(new   InputStreamReader(s1));

BufferedWriter   output   =   new   BufferedWriter(new   OutputStreamWriter(s2));


PrintWriter   print   =   new   PrintWriter(output);


while   (true)
{
String   s   =   input.readLine();
System.out.println( "来自客户端消息------- "+s);

if   (s.equals( "quit "))
{
break;
}
print.println( "服务器收到的数据----- "+s);

print.flush();
}
}
}
catch(Exception   e)
{
e.printStackTrace();
}

finally
{
try
{
if   (server   !=null   )
{
server.close();
System.out.println( "服务端关闭 ");