Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的ASCII流过滤_Java_Sockets_Stream_Ascii - Fatal编程技术网

Java中的ASCII流过滤

Java中的ASCII流过滤,java,sockets,stream,ascii,Java,Sockets,Stream,Ascii,我想编写一个类,用于Java和C之间的通信++ 关于java和C++通信的讨论很多。在这里,我不是要求如何沟通,我知道,我知道如何沟通 我创建了一个 OutputStream os = socketChannel.socket().getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter( os); BufferedWriter wr = new BufferedWriter( osw ); 然后我写 Stri

我想编写一个类,用于Java和C之间的通信++

关于java和C++通信的讨论很多。在这里,我不是要求如何沟通,我知道,我知道如何沟通

我创建了一个

 OutputStream os = socketChannel.socket().getOutputStream();
 OutputStreamWriter osw = new OutputStreamWriter( os);
 BufferedWriter wr = new BufferedWriter( osw );
然后我写

 String data= dataArea.getText();

 wr.write( dataArea.getText() );
 wr.write('\0');//here is the wire with C++
 wr.flush(); // flushes the stream

我发了一些短信:

Hi this is a test
i send also 
character as dollar $ ...
or other stange é*"£$%&/(()=?'^ìì[]@!<>#òùèé+*
and so on
Hi这是一个测试
我也发送
字符作为美元$。。。
或其他词组*“$%&/(()=?”^ìì[]@!”+*
等等
阅读两个系统之间发送的原始文本,我看到:

00000000  48 69 20 74 68 69 73 20  69 73 20 61 20 74 65 73   Hi this  is a tes 
00000010  74 0A 69 20 73 65 6E 64  20 61 6C 73 6F 20 0A 63   t.i send  also .c 
00000020  68 61 72 61 63 74 65 72  20 61 73 20 64 6F 6C 6C   haracter  as doll 
00000030  61 72 20 24 20 2E 2E 2E  0A 6F 72 20 6F 74 68 65   ar $ ... .or othe 
00000040  72 20 73 74 61 6E 67 65  20 C3 A9 2A 22 C2 A3 24   r stange  ..*"..$ 
00000050  25 26 2F 28 28 29 3D 3F  27 5E C3 AC C3 AC 5B 5D   %&/(()=? '^....[] 
00000060  40 21 3C 3E 23 C3 B2 C3  B9 C3 A8 C3 A9 2B 2A 0A   @!<>#... .....+*. 
00000070  61 6E 64 20 73 6F 20 6F  6E 00                     and so o n.
00000000 48 69 20 74 68 69 73 20 69 73 20 61 20 74 65 73 Hi这是一个tes
0000001074 0A 69 20 73 65 6E 64 20 61 6C 73 6F 20 0A 63 t.i也发送.c
00000020686172616374657220617320646F6C6C角色作为玩偶
000000 30 61 72 20 24 20 2 E 2 E 2 E 0 A 6 F 72 20 6 F 74 68 65 ar$或其他
000000 40 72 20 73 74 61 6E 67 65 20 C3 A9 2A 22 C2 A3 24 r表.*。$
000000 50 25 26 2F 28 28 29 3D 3F 27 5E C3 AC C3 AC 5B 5D%&/(()=?')^….]
000000 60 40 21 3C 3E 23 C3 B2 C3 B9 C3 A8 C3 A9 2B 2A 0A!#..+*。
000000 70 61 6E 64 20 73 6F 20 6F 6E 00等。
这接近解决方案

更改我获得的字符集“US-ASCII”

Hi这是一个测试
我也发送
字符作为美元$。。。
或其他词组*“$%&/(()=?”^ìì[]@!”+*
等等
00000000 48 69 20 74 68 69 73 20 69 73 20 61 20 74 65 73 Hi这是一个tes
00000010740A2020069207365656E6420616C73T.i发送als
000000 20 6F 20 0A 20 20 20 63 68 61 72 61 63 74 65 72 o.c角色
000000 30 20 61 73 20 64 6F 6C 6C 61 72 20 24 20 2E 2E 2E作为玩偶ar$。。。
000000 40 0A 20 20 20 6F 72 20 6F 74 68 65 72 20 73 74。或其他st
000000 50 61 6E 67 65 20 3F 2A 22 3F 24 25 26 2F 28 28 29 ange?*“?$%和/()
00000060 3D 3F 27 5E 3F 5F 5D 40 21 3C 3E 23 3F 3F 3F=?'^???[]@!#???
000000 70 3F 2B 2A 0A 20 20 61 6E 64 20 73 6F 20 6F?+*。等等
000000806e00
这接近我的目的


我只需要传输扩展字符为“è”->E8的ASCII码

然后我需要将“\0”放在字符串的末尾

“\0”是消息终止符

现在的问题是:我喜欢使用Java创建一个Writer或streamwriter来输出特定的二进制数据格式

使用
OutputStreamWriter
BufferedWriter
的正确级别是多少?我应该从头重写、扩展或使用一些库吗? 关于我喜欢做什么,有什么例子吗?
对于输入,我也会这样做

<>我喜欢用这种形式写它,因为明天我在java中重写C++服务器时,我用的是两边的DATAOuttuStudio.< /P>
使用
不是一个好的解决方案,我更喜欢Java集成的解决方案。

此流支持自动刷新,并支持US-ASCII,如您所愿

OutputStream os = socketChannel.socket().getOutputStream();
PrintStream ps = new PrintStream( os, true, "US-ASCII" );
ps.print( "tange é*"£$%&/(()=?'^ìì[]@!<>#òùèé+*" );
os.write( (byte)0 ); // end-of-message
OutputStream os=socketChannel.socket().getOutputStream();
PrintStream ps=新的PrintStream(os,true,“US-ASCII”);
ps.print(“tangeé*”£$%和/(()=?“^ìì[]@!#òùè+*”);
os.write((字节)0);//消息结束

我已经基于BufferedWriter和BufferedReader完成了一个可能的解决方案,我使用了正确的ASCII扩展字符编码ISO-8859-1



我只是简单地打开了BufferedWriter和BufferedReader的源代码,并查看了如何获得我的交互

BufferedReader不能简单地扩展,因为它使用了一些函数(应该从java Boys重写)。它扩展了缓冲读取器,但没有用



导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.Reader;
公共类TBufferReader扩展了BufferedReader{
私人读者;
私有字符cb[];
nextChar的私有内部nChars;
私有静态final int INVALIDATED=-2;
私有静态final int UNMARKED=-1;
private int markedChar=未标记;
private int readAheadLimit=0;/*仅当markedChar>0时有效*/
/**如果下一个字符是换行符,请跳过它*/
private boolean skipNUL=false;
/**设置标记时的skipLF标志*/
私有布尔值markedSkipLF=false;
私有静态int-defaultCharBufferSize=8192;
私有静态int defaultExpectedLineLength=80;
/**
*创建使用输入缓冲区的缓冲字符输入流
*指定的大小。
*
*@param在读卡器中的应用
*@param sz输入缓冲区大小
*
*@exception IllegalArgumentException如果sz=nChars){/*EOF*/
如果(s!=null&&s.length()>0){
返回s.toString();
}否则{
返回null;
}
}
布尔eol=假;
字符c=0;
int i;
/*如有必要,跳过剩余的“\0”*/
if(省略&&(cb[nextChar]='\0')){
nextChar++;
}
熟练=错误;
Omitinul=false;
charLoop:for(i=nextChar;iOutputStream os = socketChannel.socket().getOutputStream();
PrintStream ps = new PrintStream( os, true, "US-ASCII" );
ps.print( "tange é*"£$%&/(()=?'^ìì[]@!<>#òùèé+*" );
os.write( (byte)0 ); // end-of-message
OutputStream os = socketChannel.socket().getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "ISO-8859-1");
TBufferedWriter bw = new TBufferedWriter (osw);
bw.writeTMessageFlushing( dataArea.getText() );


InputStream is = socketChannel.socket().getInputStream();
InputStreamReader isr= new InputStreamReader(is, "ISO-8859-1") ;
TBufferedReader br= new TBufferedReader(isr);
// wait for response
String responseLine = br.readTMessage();
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;


public class TBufferedWriter extends BufferedWriter {


    public TBufferedWriter(Writer out){
        super( out );
    }
    public TBufferedWriter(Writer out, int sz){
        super( out, sz );
    }

    public void writeTMessage(String message) throws IOException {
         synchronized (lock) {
              super.write( message );
              super.write('\0');
         }
    }
     public void writeTMessageFlushing(String message) throws IOException {
         synchronized (lock) {
              super.write( message );
              super.write('\0');
              super.flush();
         }
    }

}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;


public class TBufferedReader extends BufferedReader {
    private Reader in;
    private char cb[];
    private int nChars, nextChar;
    private static final int INVALIDATED = -2;
    private static final int UNMARKED = -1;
    private int markedChar = UNMARKED;
    private int readAheadLimit = 0; /* Valid only when markedChar > 0 */

    /** If the next character is a line feed, skip it */
    private boolean skipNUL = false;
    /** The skipLF flag when the mark was set */
    private boolean markedSkipLF = false;
    private static int defaultCharBufferSize = 8192;
    private static int defaultExpectedLineLength = 80;


    /**
     * Creates a buffering character-input stream that uses an input buffer of
     * the specified size.
     *
     * @param  in   A Reader
     * @param  sz   Input-buffer size
     *
     * @exception  IllegalArgumentException  If sz is <= 0
     */
    public TBufferedReader( Reader in, int sz ) {
        super( in );
        if (sz <= 0) {
            throw new IllegalArgumentException( "Buffer size <= 0" );
        }
        this.in = in;
        cb = new char[ sz ];
        nextChar = nChars = 0;
    }


    /**
     * Creates a buffering character-input stream that uses a default-sized
     * input buffer.
     *
     * @param  in   A Reader
     */
    public TBufferedReader( Reader in ) {
        this( in, defaultCharBufferSize );
    }


    /** Checks to make sure that the stream has not been closed */
    private void ensureOpen() throws IOException {
        if (in == null) {
            throw new IOException( "Stream closed" );
        }
    }


    /**
     * Fills the input buffer, taking the mark into account if it is valid.
     */
    private void fill() throws IOException {
        int dst;
        if (markedChar <= UNMARKED) {
            /* No mark */
            dst = 0;
        } else {
            /* Marked */
            int delta = nextChar - markedChar;
            if (delta >= readAheadLimit) {
                /* Gone past read-ahead limit: Invalidate mark */
                markedChar = INVALIDATED;
                readAheadLimit = 0;
                dst = 0;
            } else {
                if (readAheadLimit <= cb.length) {
                    /* Shuffle in the current buffer */
                    System.arraycopy( cb, markedChar, cb, 0, delta );
                    markedChar = 0;
                    dst = delta;
                } else {
                    /* Reallocate buffer to accommodate read-ahead limit */
                    char ncb[] = new char[ readAheadLimit ];
                    System.arraycopy( cb, markedChar, ncb, 0, delta );
                    cb = ncb;
                    markedChar = 0;
                    dst = delta;
                }
                nextChar = nChars = delta;
            }
        }

        int n;
        do {
            n = in.read( cb, dst, cb.length - dst );
        } while (n == 0);
        if (n > 0) {
            nChars = dst + n;
            nextChar = dst;
        }
    }


    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\0')
     *
     * @param      ignoreNUL  If true, the next '\0' will be skipped
     *
     * @return     A String containing the contents of the line, not including
     *             any line-termination characters, or null if the end of the
     *             stream has been reached
     *
     * @see        java.io.LineNumberReader#readLine()
     *
     * @exception  IOException  If an I/O error occurs
     */
    String readTMessage( boolean ignoreNUL ) throws IOException {
        StringBuffer s = null;
        int startChar;

        synchronized (lock) {
            ensureOpen();
            boolean omitNUL = ignoreNUL || skipNUL;
bufferLoop:     for (;;) {
                    if (nextChar >= nChars) {
                        fill();
                    }
                    if (nextChar >= nChars) { /* EOF */
                        if (s != null && s.length() > 0) {
                            return s.toString();
                        } else {
                            return null;
                        }
                    }
                    boolean eol = false;
                    char c = 0;
                    int i;

                    /* Skip a leftover '\0', if necessary */
                    if (omitNUL && (cb[nextChar] == '\0')) {
                        nextChar++;
                    }
                    skipNUL = false;
                    omitNUL = false;

charLoop:               for (i = nextChar; i < nChars; i++) {
                            c = cb[i];
                            if ((c == '\0')) {
                                eol = true;
                                break charLoop;
                            }
                        }

                    startChar = nextChar;
                    nextChar = i;

                    if (eol) {
                        String str;
                        if (s == null) {
                            str = new String( cb, startChar, i - startChar );
                        } else {
                            s.append( cb, startChar, i - startChar );
                            str = s.toString();
                        }
                        nextChar++;
                        if (c == '\0') {
                            skipNUL = true;
                        }
                        return str;
                    }

                    if (s == null) {
                        s = new StringBuffer( defaultExpectedLineLength );
                    }
                    s.append( cb, startChar, i - startChar );
                }
        }
    }


    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
     * followed immediately by a linefeed.
     *
     * @return     A String containing the contents of the line, not including
     *             any line-termination characters, or null if the end of the
     *             stream has been reached
     *
     * @exception  IOException  If an I/O error occurs
     *
     * @see java.nio.file.Files#readAllLines
     */
    public String readTMessage() throws IOException {
        return readTMessage( false );
    }
}