当前位置: 代码迷 >> J2SE >> Java tcp ip协议多次通讯出有关问题了
  详细解决方案

Java tcp ip协议多次通讯出有关问题了

热度:535   发布时间:2016-04-23 20:42:42.0
Java tcp ip协议多次通讯出问题了
用TCP/IP协议实现客户端与服务器端通讯,其中服务器端不是自己写的,只写客户端,
协议要求如下:
1.发送"Connect"命令,服务器返回“DATA RECEIVE PASSWORD"
2.发送密码”01234567“,服务器返回”CONNECT OK!"

我写了一个客户端,实现了TCP/IP的连接,通过DataOutputStream建立了输入流,同时将字符型数据转化成字节型在console中输出了,但当做第二步时,不知道怎么回事,发送密码后,服务器无法返回回应,不知道错在哪里,请指教,源代码如下:

import java.net.*;
import java.io.*;

public class ByteClient {

private int clientNumber;  
    private SocketAddress address;  
    public ByteClient(int clientNum) {  
        clientNumber = clientNum;  
    }  
public void setupClients(String serverHostName, int port) throws IOException {  
        address = new InetSocketAddress(serverHostName, port);  
            System.out.println();  
            System.out.println("start client No. 1");  
            Socket socket = new Socket();  
            socket.connect(address);  
          //ADD
            byte[] hello = "Connect".getBytes(); 
            byte[] helloreturn="DATA RECEIVE PASSWORD...".getBytes();
            byte[] code="01234567".getBytes();
           
                    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());  
            dos.write(hello, 0, hello.length);
            DataInputStream bufferedReader = new DataInputStream(socket.getInputStream());  
            byte[] cbuff = new byte[256];  
            char[] charBuff = new char[256]; 
            int size = 0;  

            //ADD 判断是否接收到DATA RECIEVE PASSWORD
            while( (size = bufferedReader.read(cbuff))> 0) {  
                convertByteToChar(cbuff, charBuff, size);  
                System.out.println(charBuff);//Console中显示了已收到的数据“DATA RECIEVE PASSWORD
            }
                //ADD
            dos.write(code,0,code.length);//重复以上收发过程,怎么没有结果?
            while( (size = bufferedReader.read(cbuff))> 0) {  
                convertByteToChar(cbuff, charBuff, size);  
                System.out.println(charBuff);
              //ADD END
            }  
           
           // bufferedReader.close();  
            //socket.close();  
        }  
   

private void convertByteToChar(byte[] cbuff, char[] charBuff, int size) {  
        for(int i=0; i<charBuff.length; i++) {  
            if(i < size) {  
                charBuff[i] = (char)cbuff[i];  
            } else {  
                charBuff[i] = ' ';  
            }  
        }  
  相关解决方案