Solutions to Chinese garbled characters in Java Socket and C # Communication

Source: Internet
Author: User

Recently, I am working on a project. One of the problems is the communication between Java and. net. The specific problem is as follows:

The client uses Java and the server uses C #. The two use TCP-based socket communication. However, in a small test example, all the results from the client are garbled. So I hope I can find a solution through the Internet. However, there are a lot of answers on the Internet. After a lot of experiments, it cannot be solved well. There is no way to troubleshoot by yourself.

After some efforts, I finally found the reason: C # and Java have different encoding methods. Although I found the cause, the answer to this question on the Internet is also a matter of contention. The source code is provided here, hoping to help everyone.

The first is the client's Java code (this is relatively simple)

Import java.net. *; import Java. io. *; public class tcpcline {public static void main (string [] ARGs) throws exception {try {// the IP address here is the IP address of the server, unified socket S = new socket ("ip address", Port); outputstream OS = S. getoutputstream (); dataoutputstream dos = new dataoutputstream (OS); string sendstr = "Hello! Hello "; // note here," UTF-8 "byte [] BS = sendstr in getbytes. getbytes ("UTF-8"); // here is the use of write (), not writeutf (), as to why, you can view the Java help documentation, which explains dos. write (BS, 0, BS. length); // the following two sentences are not used here, because when we close the client, the server can also record which client is offline. // dos. close (); // s. close ();} catch (connectexception connexc) {connexc. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();}}}

C # server-side code, which is explained here. We put the server-side code into a class library tcpserver.

The following is the Error Log Code (messages sent by the client and offline notifications are put here)

Using system. collections. generic; using system. LINQ; using system. text; using system; namespace tcpserver {// <summary> // Error Log class // </Summary> public class loghelper {public static readonly object objlock = new object (); /// <summary> /// write errors. log File // </Summary> /// <Param name = "MSG"> error message </param> /// <Param name = "ex"> exception </param> Public static void err (string MSG, exception ex) {string S = ""; I F (ex! = NULL) {S = "Err:" + MSG + ":" + ex. message;} else {S = MSG;} // output the error to the log file string filename = appdomain. currentdomain. basedirectory + "log/" + convert. tostring (getunixtime () + ". log "; lock (objlock) {using (system. io. streamwriter Sw = new system. io. streamwriter (filename, true) {SW. writeline (s); If (ex! = NULL) {SW. writeline (ex. stacktrace);} SW. writeline ("time:" + datetime. now. tostring (); Sw. writeline ("----------------------------------");}}}

Serverlisten class

Using system. collections. generic; using system. LINQ; using system. text; using system. net; using system. net. sockets; using system. threading; using system; namespace tcpserver {public class serverlisten {public static void run (Object igetclientdata) {ipendpoint serverip = new ipendpoint (IPaddress. parse ("ip address"), Port); // The pre-used IP address and port socket skserver = new socket (addressfamily. interNetwork, sockettype. stream, protocoltype. TCP); skserver. BIND (serverip); skserver. listen (100); // maximum number of connected clients while (true) {socket skclient; try {// execute when an available client connection attempt is made and a new socket is returned, it is used to communicate with the client. skclient = skserver. accept ();} catch (exception ex) {loghelper. err ("failed to receive user connection serverlisten. run socket. accept ", ex); continue;} thrclient thrc = new thrclient (skserver, skclient, (igetclientdata); thread t = new thread (thrc. run); T. start ();}}}}

Thrclient class

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. net; using system. net. sockets; using system. threading; namespace tcpserver {public class thrclient {Private Static readonly stringbuilder sb = new stringbuilder (); Private socket skserver; private socket skclient; private ipendpoint clientip; private igetclientdata; // Private byte [] Senddata; // The sent message private byte [] receivedata = new byte [1024]; // The received message private int receiven; private int netid; /// <summary> /// thrclient constructor // </Summary> /// <Param name = "pskserver"> server </param> /// <Param name = "pskclient"> client </param> Public thrclient (socket pskserver, socket pskclient, igetclientdata) {This. skserver = pskserver; this. skclient = pskclient; this. igetclientdata = Igetclientdata; this. clientip = (ipendpoint) This. skclient. remoteendpoint; // you must use utf8 instead of uncode this. senddata = encoding. utf8.getbytes ("success"); try {This. skclient. send (senddata, senddata. length, socketflags. none); // send information} catch (exception ex) {loghelper. err ("send the first successful connection information thrclient. thrclient socket. send ", ex) ;}} public void run () {While (true) {try {This. token en = skclient. receive (this. Receivedata); // receives if (this. En en! = 0) {string removemsg = encoding. utf8. getstring (receivedata, 0, receiven); igetclientdata. getthread (removemsg) ;}} catch (exception ex) {igetclientdata. getclientip (ipendpoint) skclient. remoteendpoint ). address); break ;}}}}

The above is the main code, and there is an interface provided to the outside world, which will not be posted here.

The communication problem between the two languages is really a headache. We guessed it and found the answer after several experiments. So, as mentioned in "big talk Design Patterns", we are not obsessed with success.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.