手记

socket网络编程(中文乱码问题)

1.客户端

[代码]java代码:

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

package Demo01;

 

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.net.Socket;

 

public class Client   {

 

public static void main(String[] args) {

 

try {

Socket socket=new Socket("127.0.0.1",8810);

BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));

   String str="我是中国人!";

   bw.write(str);

   bw.close();

   socket.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

 

}

 

2.服务器端

[代码]java代码:

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

package Demo01;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.ServerSocket;

import java.net.Socket;

 

public class Server   {

 

public static void main(String[] args) {

 

try {

ServerSocket socket=new ServerSocket(8810);

System.out.println("服务器已经启动.....请连接");

   Socket   socket2=socket.accept();

   BufferedReader br=new BufferedReader(new InputStreamReader(socket2.getInputStream(),"UTF-8"));

   int r;

   while((r=br.read())!=-1){

    System.out.print((char)r);

   }

   System.out.println();

   br.close();

   socket2.close();

   socket.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

 

}

原文链接:http://www.apkbus.com/blog-813041-60921.html

0人推荐
随时随地看视频
慕课网APP