最近在学java网络编程,但遇到一个问题百思不得其解:
PrintWriter output=new PrintWriter(clientSocket.getOutputStream(),true);
上面这行是用来输出的吗?就是发消息的?BufferedReader d=new BufferedReader(new InputStreamReader(sc.getInputStream()));
而这一行是用来收消息的吗?对于一个socket,我理解,就像一个文件一样,它的输入应该对应我们要发的消息吧,就是getInputStream()应该对应发消息的啊,跟上面不一致啊.这是概念上的一个模糊.望大家指点另一个问题就是:
在客户端和服务端,我的收消息部分是这么写的:服务端:
BufferedReader d=new BufferedReader(new InputStreamReader(sc.getInputStream()));
BufferedInputStream(sc.getInputStream()));
 while(true)
  { 
String strIn=d.readLine();
if(strIn.equals("End"))
break;
if(strIn!=null)
{
System.out.println("收到了一条消息---by 服务端");
}
  }对于客户端:
BufferedReader d=new BufferedReader(new InputStreamReader(sc.getInputStream()));
BufferedInputStream(sc.getInputStream()));
 while(true)
  { 
String strIn=d.readLine();
if(strIn.equals("End"))
break;
if(strIn!=null)
{
System.out.println("收到了一条消息---by 客户端");
}
  }我的本意是两端收到消息后不处理,只打出相应的字符串.
但实际效果是:
两边同时打出"收到了一条消息---by 客户端"或"收到了一条消息---by 服务端"!!!!!!!
就是两边显示的是一样的.我很奇怪.
-------------------------------
贴上全码,以便纠错:
服务端:
import java.io.*;
import java.net.*;public class ChatEx
{
public static void main(String[] args)
{
ChatThread ce=new ChatThread(8888);
ce.run();
}
}class ChatThread
{
private int strPort=0;
public ChatThread()
{
}
public ChatThread(int strPort)
{
this.strPort=strPort;
}
public void run()
{
Socket chats=null;
if(strPort==0)
{
System.out.println("端口没有初始化,程序将退出!");
return;
}
String strIn=new String("");
ServerSocket ss;
try
{
ss=new ServerSocket(strPort);
System.out.println("正在监听"+ss.getLocalPort()+"端口......");
chats=ss.accept();

System.out.println("连接成功!");

//新线程用来收信息
ChatRecThread crt=new ChatRecThread(chats);
Thread t=new Thread(crt);
t.start();

//发消息部分
PrintWriter output=new PrintWriter(chats.getOutputStream(),true); while(true)
{
System.out.print("安1:");
BufferedReader bout = new BufferedReader(new InputStreamReader(System.in)); 
String strOut = bout.readLine();
if(strOut!=null)
{
output.println(strOut);
}
else if(strOut.equals("End"))
break;
}
output.close();
chats.close();
}
catch(Exception e)
{System.out.println("error--"+e.getMessage());}
System.out.println("over");
}
}class ChatRecThread implements Runnable
{
private Socket sc;
public ChatRecThread()
{
}
public ChatRecThread(Socket sc)
{
this.sc=sc;
}
public void run()
{
try
{
BufferedReader d=new BufferedReader(new InputStreamReader(sc.getInputStream()));
while(true)
{
String strIn=d.readLine();
if(strIn.equals("End"))
break;
else if(strIn!=null)
{
System.out.println("收到了一条消息---by ChatEx");
}
else
System.out.println("here!");
}
sc.close();
d.close();
}
catch(Exception e)
{System.out.println(e);}
}
}
-----------------------------------
客户端:
import java.io.*;
import java.net.*;
public class SocketCC
{
public static void main(String[] args)
{
try
{
Socket clientSocket =new Socket ("127.0.0.1",8888);//创建一个流Socket并与主机mice上的端口9000相连接

//新线程用来输入
ChatRecThread crt=new ChatRecThread(clientSocket);
Thread t=new Thread(crt);
t.start();

//输出部分
PrintWriter output=new PrintWriter(clientSocket.getOutputStream(),true);
while(true)
{
System.out.print("邹1:");

//键盘输入部分
BufferedReader bout = new BufferedReader(new InputStreamReader(System.in)); 
String strOut = bout.readLine();
if(strOut!=null)
{
output.println(strOut);
}
if(strOut.equals("End"))
break;
}
output.close();
clientSocket.close();
}
catch (Exception e)
{
System.err.println("Exception :"+e);
}
}
}class ChatRecThread implements Runnable
{
//String strIn;
private Socket sc;
public ChatRecThread()
{
}
public ChatRecThread(Socket sc)
{
this.sc=sc;
}
public void run()
{
try
{
BufferedReader d=new BufferedReader(new InputStreamReader(sc.getInputStream()));
while(true)
{
String strIn=d.readLine();
if(strIn.equals("End"))
break;
else if(strIn!=null)
{
System.out.println("SocketCC收到了一条消息---by SocketCC");
}
else
System.out.println("here");
}
sc.close();
d.close();
}
catch(Exception e)
{System.out.println(e);}
}
}
--------------------------------------
谢谢大家了!

解决方案 »

  1.   

    帮你找了个例子,看看!~package com.davidflanagan.examples.net;
    import java.io.*;
    import java.net.*;
    public class UDPSend {
        public static final String usage = 
    "Usage: java UDPSend <hostname> <port> <msg>...\n" +
    "   or: java UDPSend <hostname> <port> -f <file>";    public static void main(String args[]) {
            try { 
                // Check the number of arguments
                if (args.length < 3) 
                    throw new IllegalArgumentException("Wrong number of args");
                
                // Parse the arguments
                String host = args[0];
                int port = Integer.parseInt(args[1]);
        
                // Figure out the message to send.  
                // If the third argument is -f, then send the contents of the file
                // specified as the fourth argument.  Otherwise, concatenate the 
                // third and all remaining arguments and send that.
                byte[] message;
                if (args[2].equals("-f")) {
                    File f = new File(args[3]);
                    int len = (int)f.length();    // figure out how big the file is
                    message = new byte[len];      // create a buffer big enough
                    FileInputStream in = new FileInputStream(f);
                    int bytes_read = 0, n;
                    do {                          // loop until we've read it all
                        n = in.read(message, bytes_read, len-bytes_read);
                        bytes_read += n;
                    } while((bytes_read < len)&& (n != -1));
                }
                else { // Otherwise, just combine all the remaining arguments.
                    String msg = args[2];  
                    for (int i = 3; i < args.length; i++) msg += " " + args[i];
                    message = msg.getBytes();
                }
                
                // Get the internet address of the specified host
                InetAddress address = InetAddress.getByName(host);
        
                // Initialize a datagram packet with data and address
                DatagramPacket packet = new DatagramPacket(message, message.length,
           address, port);
        
                // Create a datagram socket, send the packet through it, close it.
                DatagramSocket dsocket = new DatagramSocket();
                dsocket.send(packet);
                dsocket.close();
            }
            catch (Exception e) {
                System.err.println(e);
        System.err.println(usage);
            }
        }
    }
      

  2.   

    java输入输出流是以流为参照物的,in就是输入到流中,屏幕是system.in是标准的输入流,如:键盘,屏幕显示就是标准输出流
      

  3.   

    如果in就是输入到流中,是从键盘输入到输入输出设备流,就是程序想发送的消息是吧
    那么发消息用的代码:
    PrintWriter output=new PrintWriter(clientSocket.getOutputStream(),true);
    怎么是用的getOutputStream()呢?用的是获得输出流的,输出流应该对应我们程序收到的消息啊.
      

  4.   

    相关部分你应该这样写:System.out.println("\n收到了一条消息:"+strIn);