Java实现TCP互发消息

2025-05-29 0 55

本文实例为大家分享了Java实现TCP互发消息的具体代码,供大家参考,具体内容如下

TCP客户端:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40
package tcp;

import java.io.IOException;

import java.io.OutputStream;

import java.net.InetAddress;

import java.net.Socket;

public class TcpClient {

public static void main(String[] args) {

Socket socket =null;

OutputStream os =null;

try {

//创建socket对象,指明服务器端的ip和端口号

InetAddress inet = InetAddress.getByName("127.0.0.1");

socket = new Socket(inet, 8888);

//获取一个输出流,用于输出数据

os = socket.getOutputStream();

//写出数据的操作

os.write("你好,我是客户端".getBytes());

}catch(IOException e){

e.printStackTrace();

}finally {

//资源的关闭

if(os!=null){

try{

os.close();

}catch (IOException e){

e.printStackTrace();

}

}

if(socket!=null){

try {

socket.close();

}catch (IOException e){

e.printStackTrace();

}

}

}

}

}

TCP服务端:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68
package tcp;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.ServerSocket;

import java.net.Socket;

class TcpServer{

public static void main(String[] args) {

ServerSocket ss=null;

Socket socket=null;

InputStream is=null;

ByteArrayOutputStream baos =null;

try {

//创建服务器端的ServerSocket,指明自己的端口

ss = new ServerSocket(8888);

//调用accept()表示接收来自于客户端的socket

socket = ss.accept();

//获取输入流中的数据

is = socket.getInputStream();

/*读取输入流中的数据(ByteArrayOutputStream可以把字节一次性记录下来,

这样就可以避免一些字符的字节码不一致导致发送后解析出现乱码;

ByteArrayOutputStream的功能与StringBuilder的作用有异曲同工之妙。)

*/

baos = new ByteArrayOutputStream();

byte[] buffer = new byte[5];

int len;

while ((len = is.read(buffer)) != -1) {

baos.write(buffer, 0, len);

}

System.out.println(baos.toString());

}catch (IOException e){

e.printStackTrace();

}

finally{

//关闭流

if (baos!=null){

try {

baos.close();

}catch (IOException e){

e.printStackTrace();

}

}

if (is!=null){

try {

is.close();

}catch (IOException e){

e.printStackTrace();

}

}

if (socket!=null){

try {

socket.close();

}catch (IOException e){

e.printStackTrace();

}

}

if (ss!=null){

try {

ss.close();

}catch (IOException e){

e.printStackTrace();

}

}

}

}

}

注意:在Intellij idea中运行时,需先打开两个端的平行运行设置,操作如下:

Java实现TCP互发消息

Java实现TCP互发消息

最后的运行结果如下:

Java实现TCP互发消息

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/weixin_45802810/article/details/107623345

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java实现TCP互发消息 https://www.kuaiidc.com/119485.html

相关文章

发表评论
暂无评论