SOCKET communication problems between java and C #

SOCKET communication problems between java C # and
a server-side (using java prepared)
/ **
* listening client request
*
* /
Private static void socketService ()
{
ExecutorService = Executors.newCachedThreadPool Exec ();
the try
{
   the ServerSocket Server = the ServerSocket new new (5678);
   int I =. 1;
   the while (to true)
   {
    MyLogManager.InfoLog (log, null, "waiting for connection of the" + i + "users ...");
    the try
    {
     the Socket = server.accept Client () ;
     MyLogManager.InfoLog (log, null, "second" + i + "user connection is completed!");
     exec.execute (new new PDAServerWithDB (Client));
    }
    the catch (Exception whileExp)
    {
     String MSG = "connection failed multithreading ! ";
     MyLogManager.ErrorLog(log, whileExp, msg);
    }
    i++;
   }
}
catch(IOException ioe)
{
   String msg = "连接失败!";
   MyLogManager.ErrorLog(log, ioe, msg);
   exec.shutdown();
}
}

DETAILED Socket for receiving and transmitting information processing PDAServerWithDB class
information processing are divided into: receiving and sending data
server receives all data using the ReadLine () method, which requires the client to have a transmission request line terminator.
Code for receiving a data transmission server
a). Configuration input and output streams
the InputStream s.getInputStream INPUT = ();
the OutputStream s.getOutputStream OUTPUT = ();
the PrintWriter outWriter the PrintWriter new new = (OUTPUT);
the BufferedReader inputReader the BufferedReader new new = (the InputStreamReader new new (INPUT));
B. Receiving a client request code
String = inputReader.readLine Request ();
Request request.trim = ();
Request = request.replaceAll ( "\ n-", "");
C. Sends data to the client code text
outWriter.println (strInfo);
outWriter.flush ();
D). Code is sent to the client a file
// length of sending files
File file = new File (filePath) ;
byte [] = outBytes new new byte [1024];
int COUNT = 0;
the FileInputStream = new new FileInput the FileInputStream (File);  
ByteArrayOutputStream ByteArrayOutputStream new new OW = ();  
the while ((COUNT = fileInput.read (outBytes))> 0) {
MyLogManager .DebugLog (log, null, String.valueOf (COUNT));
ow.write (outBytes, 0, COUNT);
}   
outPut.write (ow.toByteArray ());
//outWriter.print(ow);// this can properly respond when JAVA client, but can not respond in C # client.
//outWriter.flush ();


Second, the client (java and c # use two versions)
. 1) transmission request information (string format)
to JAVA is: directly println PrintWrite class () method.
For C # is: required socket.Send (System.Text.Encoding.ASCII.GetBytes (msg + "\ r")); msg need to request information plus a back end of line flag.
2) The received data (or text files)
2-1) .java client receives the data
A). java text received code example:
****** code sample *****
log.info ( "connecting to the server");
InetAddress address = InetAddress.getByName (AppConfig.IP); // 193.100.100.143);
SC = the SocketChannel.open the SocketChannel (the InetSocketAddress new new (address, AppConfig.PORT));
   
log.info ( "server connection is successful");
// initialize flow connection is successful
the inputStream inputStream = Channels.newInputStream (SC);
the InputStreamReader new new IS = the InputStreamReader (inputStream, "GBK");
in the BufferedReader new new = (IS);

log.info ( "data reception server");           
String responseLine = "";
the while (! (responseLine = in.readLine ()) = null)
{
// readLine received data is automatically discarded line breaks, if for holding data format, here you need to add a line break identifier
returnStr + = responseLine + "\ n-";
}     
log.info ( "server data reception is completed");
************* *

Sample Code b) java file received:
***** ***** Code Example
log.info ( "connecting to the server");
InetAddress = InetAddress.getByName address ( "193.100.100.159"); // 193.100 .100.143);
the SocketChannel the SocketChannel.open SC = (the InetSocketAddress new new (address, AppConfig.PORT));
   
log.info ( "server connection is successful, the flow starts initialization");   
// initialize the connection is successful stream
OutputStream outputStream = Channels.newOutputStream ( SC);
the inputStream inputStream = Channels.newInputStream (SC);
the InputStreamReader = new new InputStreamReader the InputStreamReader (inputStream);

byte[] b = new byte[1024];
ByteArrayOutputStream bArrStream = new ByteArrayOutputStream(fileLength);
int readCount = 0;
while ((readCount = inputStream.read(b)) != -1)
{
log.info(readCount);
bArrStream.write(b, 0, readCount);
}

log.info ( "size:" + bArrStream.toByteArray () length.);
log.info ( "Server data reception is completed");
**************
2-2). c # client receives the data code
a) receiving text data.
***** code sample *****
the Socket socket = null;
the MemoryStream memStream = null;
String returnMsg = string.Empty;
// establish a connection to the server
socket = the Socket new new (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
the IPAddress = IPAddress.Parse the Add (appConfig.Ip);
the IPEndPoint Endpt the IPEndPoint new new = (the Add, appConfig.Port);
Socket.connect (Endpt);
// receive data
byte [] Buffer = new new byte [1024];
int RECCOUNT = 0;
memStream the MemoryStream new new = ();
byte stream received // returned
while ((recCount = socket.Receive (buffer ))> 0)
{
MemStream.Write (Buffer, 0, RECCOUNT);
}
Encoding encoding = Encoding.GetEncoding ( "GBK");
returnMsg = encoding.GetString (memStream.GetBuffer (), 0, memStream.GetBuffer () the Length.);
** ************
. B) receiving a data file
**** **** Code example
// receive data
byte [] Buffer = new new byte [1024];
int RECCOUNT = 0;
the MemoryStream memStream the MemoryStream new new = ();
the while ((RECCOUNT = Socket.Receive (Buffer))> 0)
{
memStream.Write (Buffer, 0, RECCOUNT);
}
// Next, according to the file format, the file can be saved as memStream
* *************

======= These are the final version of the code used ===========
problems in the development process and their solutions
1.) text garbled
java server-side code files are encoded using GBK . Therefore, conversion GBK encoding used to read when the client.
2.) interaction client and server.
The service uses the PrintWriter class to encapsulate transmission data stream (transmission data), new BufferedReader (new InputStreamReader ( InputStream)) to encapsulate the input stream (read data)
server when the read data is performed using ReadLine method, it requires the client there is a need to terminate a line when sending the request. Java is used for println () can be,
and needs to be added to the C # end of a row identifier "\ r" after the manual transmission information.
For the service side of the feedback information feedback scheme, there are two, one is the println (), is a write (byte []). The former is to send a text, which is to send the file.
When sending a file using the print (object) method, java but the client receive data correctly, and the C # client can not, so it uses a write (byte []) transmission method.
When receiving data, text data should be transmitted to the end of the processing by row
the treatment java c # and the same, but different from the case of method names
STR = str.trim ();
STR = str.replaceAll ( "\ R & lt", "");
STR = str.replaceAll ( "\ n-", "");


Reproduced in: https: //www.cnblogs.com/kevinGao/archive/2011/12/19/2294466.html

Guess you like

Origin blog.csdn.net/weixin_34221036/article/details/93357454