Server:public class Server { private static final int PORT = 8000;

public static BufferedReader in;
public static PrintWriter out; Server() {
ServerSocket s;
try {
s = new ServerSocket(PORT);
 
Socket socket = s.accept();

in = new BufferedReader(new InputStreamReader( 
socket.getInputStream()));  out = new PrintWriter(new BufferedWriter( 
new OutputStreamWriter( 
socket.getOutputStream())), true); 

} catch (IOException e) {
e.printStackTrace();
}
}}Client:public class Client { private static final int PORT = 8000; public static BufferedReader in;
public static PrintWriter out; Client() throws IOException { InetAddress addr; addr = InetAddress.getByName(null); Socket socket = new Socket(addr, PORT);
  in = new BufferedReader(new InputStreamReader( 
socket.getInputStream()));  out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);  }
}上面的代码建立起了一个连接。比如说:A和B对话
Server:  out.print("你好吗?");
Client:  System.out.println(Server.in.readLine());可以这样么?

解决方案 »

  1.   

    一般Server 和 Client 不在一起吧~ Server.in.readLine() Server 不一定能看见 没有创建对象吧!我也不太懂 !~
      

  2.   

    这样怎么可能呢,一楼的
    Socket通信跟你的控制台是没有关系的,你out.print("你好吗?"); 只是输出到控制台上,而Socket是网络通信,通信里需要根据输入输出来发送和接收的:
    在客户端你要:
    //新建Socket通信
    Socket socket = new Socket(ip,port);
    //通信输出字节流
    OutputStream out = socket.getOutputStream();
        out.write(send);
        out.flush();
        log.info("send:"+sendstring);
        
        //-----------开始接收-------------
        byte[] buf = new byte[65536];
        InputStream in=socket.getInputStream();
        int count = in.read(buf);
        log.info("recieve:" + count +" bytes: ");
        returnstring = new String(buf,"GBK");在服务器端:         //报文体缓冲区
             byte[] bodybuf = new byte[bodylength];
    while(true){   
           readCount = in.read(curbuf);//读取一次最大可读数
           log.info("当前收到"+readCount+"字节");   
           System.arraycopy(curbuf, 0, bodybuf, hasReceivedBody, readCount);//将该数全额复制到bodybuf可读长度中
           hasReceivedBody +=readCount;//已收到
           log.info("已收到"+hasReceivedBody+"字节");
           if(hasReceivedBody==bodylength)break;
           readCount=0;
           }---------------------
    这段程序能说明这个问题,自己看看喽
      

  3.   

    你的代码没有socket.close()。
    -----------------------------------------------------
    比如说:A和B对话
    Server:     out.print("你好吗?");
    Client:     System.out.println(in.readLine()); 
    -----------------------------------------------------
    这个没有问题。。但是不是Server.in.readLine();
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;public class Client {    private static final int PORT = 8000;    public static BufferedReader in;
        public static PrintWriter out;    Client() throws IOException {        InetAddress addr;        addr = InetAddress.getLocalHost();        Socket socket = new Socket(addr, PORT);        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                    .getOutputStream())), true); 
            out.print("hello");
    out.flush();
    socket.close();
        }
        
    public static void main(String[] args) {
    try {
    new Client();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;public class Server {
    private static final int PORT = 8000; public static BufferedReader in; public static PrintWriter out; Server() {
    ServerSocket s;
    try {
    s = new ServerSocket(PORT);
    Socket socket = s.accept();
    in = new BufferedReader(new InputStreamReader(socket
    .getInputStream()));
    System.out.println(in.readLine());
    socket.close();

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

    public static void main(String[] args) {
    new Server();
    }
    }
      

  4.   

    呵呵,看你的实现机制了,长期保持着这个连接是可以的,没有消息的情况他会处于block状态,因为大量的开关方式对系统开销很大。如果你要实现qq这样的软件,建议使用unblocking socket或者使用udp,这种传统的方式实现的开销太大。
      

  5.   

    并不是要像QQ那样,虽然是要传送 信息,但要保证不能丢失  所以不能用UDP像我这样建立好了连接  然后通过 in 和 out往流中写数据   另一边再接收  ,这样有问题么?
      

  6.   

    没有问题,但是如果你有很多的客户端的话,最好server端一个socket一个线程while (true)
    {
       Socket socket = s.accept();
       Runnable r = new ThreadedEchoHandler(socket);   Thread t = new Thread(r);
       t.start();
    }
    像这样。
      

  7.   

    嗯。。你记得每次socket连接完成后要关闭,最后要关闭serverSocket,然后writer完后,flush()一下保证写完的数据强制被发送出去。
      

  8.   

    我这个是象棋程序   想实现网络 对战所以 我new好 服务器  和 客户端 , 然后在棋子走动的时候就  把信息传给令一边所以在传送信息的时候我就调用  定义好的静态的      public static BufferedReader in;    public static PrintWriter out;
    可是调用的时候总是说空指针...
      

  9.   

    把socket 和 serverSocket, 关闭了 那连接不是也关闭了?
      

  10.   

    那每次都要NEW  一个新server 和  Client出来?
      

  11.   

    你如果hold这个连接也没有问题。
      

  12.   

    哦~  唉~  还是晕啊~给你说说我的程序~A ,B  2个人下象棋一个人是服务器  一个人是客户端
     server 和client 连接好后  我在server和client都保留了 这2个流
    public   static   BufferedReader   in;
    public   static   PrintWriter   out; A走了一步棋就调用out.print();把信息发给BBin.readLine 接收,然后做出响应。   B走完后....这样能实现么?
      

  13.   

    in.readLine();接收的时候有没有什么好的方法,我怎么知道 另一边什么时候发送了呢?
      

  14.   

    接收有什么好的方法,就是read,readLine什么的。。呵呵,如果没有数据,你的程序会block住的。。
      

  15.   

    一般的  比如说视频信息         像QQ游戏那样用的不都是TCP的连接么?他们怎么实现连接的呢?别说他们用的不是JAVA啊~
      

  16.   

    呵呵。你说对了,qq不是用java不知道是vc还是delphi,qq用的是udp协议,msn用的是socket
      

  17.   

    汗~  那JAVA用TCP实现 像我这种是很费劲的啊?
    还不如用UDP!
      

  18.   

    就根据原先的socket写下去啊。。不过还是建议你看看java的socket,这样你写起来就不会不清楚了。
      

  19.   

    server端要用循环
    客户端也可以用循环Server端代码import java.net.*;
    import java.io.*;public class Server { private ServerSocket ss;
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    Server()
    {
    try
    {
    ss = new ServerSocket(10000);
    while (true)
    {
    socket = ss.accept();
    String remoteIP = socket.getInetAddress().getHostAddress();
    String remotePort = ":" + socket.getLocalPort();
    System.out.println("A Client come in: " + remoteIP + remotePort);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String line = in.readLine();
    System.out.println("Receive message from client:" + line);
    out = new PrintWriter(socket.getOutputStream());
    out.println("your message received.");
    out.close();
    in.close();
    socket.close();
    }
    }catch(IOException e)
    {
    System.out.println(e);
    }
    } /**
     * @param args
     */
    public static void main(String[] args) 
    {
    new Server();
    }
    }客户端代码import java.net.*;
    import java.io.*;public class Client { private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    Client()
    {
    try
    {
    while(true)
    {
    System.out.println("try to connet to 127.0.0.1:10000");
    socket = new Socket("127.0.0.1",10000);
    System.out.println("Server is connected.");
    BufferedReader line = new BufferedReader(new InputStreamReader(System.in));
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream(),true);
    System.out.println("please input some messages.");
    String ss = line.readLine();
    out.println(ss);
    System.out.println(in.readLine());

    in.close();
    out.close();
    socket.close();
    if (ss.length() == 0)
    {
    break;
    }
    }
    }catch(IOException e)
    {
    System.out.println(e);
    }

    }
    /**
     * @param args
     */
    public static void main(String[] args) 
    {
    new Client();
    }}
      

  20.   

    TO rabbitbug那像你那样不是就每次都起新的连接了么?
      

  21.   

    呵呵,你可以完全保持你的连接,只是你没有发送命令的时候,你的socket处于堵塞状态,比如你可以通过发送"end","close"之类的命令表示关闭连接,具体看你自己的实现。
      

  22.   

    我的象棋程序主要就是需要:1.A走完棋后,向B发送消息
    2.B走完后,向A发送消息通知其实这样用UDP 刚刚好~但是要保证消息必须送到呀~  这样用UDP就不行了~只能用TCP~
      

  23.   

    我的程序  就是一个人走完棋后  向另一个人发送消息 
    其实这样用UDP 就可以了~  但是UDP不能100%保证送达所以要用UDP啊~
      

  24.   

    上面的代码建立起了一个连接。 比如说:A和B对话 
    Server:     out.print("你好吗?"); 
    Client:     System.out.println(Server.in.readLine()); 可以这样么? -----------------------------------------------------lz的想法很好啊...也是可以实现的....不会实现的是技术不行..
      

  25.   

    唉~   看来我对TCP的理解  差太多~~
    我现在用TCP+UDP 实现了!大家还有兴趣的  再给我指点指点~~  周日结贴~~~~
      

  26.   

    import java.io.*;
    import java.net.*;
    public class TcpServerThread extends Thread
     {private Socket m_soc;
      private int m_id;
      public TcpServerThread(Socket s,int id)
      {m_soc=s;
       m_id=id;
       }
      public void run()
      { try
         {InetAddress ip=m_soc.getInetAddress();
          System.out.println("客户机["+m_id+"]连接成功");
          DataOutputStream out=new DataOutputStream(m_soc.getOutputStream());
          out.writeUTF("欢迎你,客户机:"+m_id);
          DataInputStream in=new DataInputStream(m_soc.getInputStream());
          String str=in.readUTF();
          while(!str.equals("quit"))
          {System.out.println("From["+m_id+"]收到:"+str);
            str=in.readUTF();
           }
         }catch(Exception e){System.out.println("错误:"+e);}
         finally
         {try {System.out.println("客户机【"+m_id+"】离开");m_soc.close();}
          catch(Exception e) {System.out.println("错误:"+e);}
        }
     }public static void main(String[] args) {
     int n=1;
     ServerSocket server=null;
     try{server=new ServerSocket(8000,10);}
         catch(Exception e) {System.out.println("Error:"+e);}
         while(true)
         {try
            {System.out.println("等待客户机【"+n+"】连接");
             Socket soc=server.accept();
             TcpServerThread tcpthread=new TcpServerThread(soc,n);
             tcpthread.start();
              n++;
            }
          catch(Exception e) {System.out.println("错误:"+e);}
         }
         }
       }
      

  27.   

    import java.io.*;
     import java.net.*;
     public class TcpClientThread {
       public static void main(String[] args)
       {Socket soc=null;
        DataInputStream in=null;
        DataOutputStream out=null;
        String strin=null;
        try
        {
          soc=new Socket("localhost",8000);
           System.out.println("正连接服务器Localhost……");
           in=new DataInputStream(soc.getInputStream());
           out=new DataOutputStream(soc.getOutputStream());
           strin=in.readUTF();
           System.out.println("服务器:"+strin);
           byte bmsg[]=new byte[20];
           String msg=new String(bmsg,0);//从第一开始
           msg=msg.trim();
           while(!msg.equals("quit"))
           {out.writeUTF(msg);
            System.in.read(bmsg);
            msg=new String(bmsg,0);
            msg=msg.trim();
            }
             out.writeUTF(msg);
             in.close();
             out.close();
             soc.close();
             }
             catch(Exception e) {System.out.println("错误:"+e);}
           }
        }