一个java 的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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161 |
import java.io.*; import java.net.*; import java.util.Scanner; public
class client { public
static void main(String[] args) { work.link(); new
MyworkWriter().start(); } } class
work { //是否在线 static
boolean online= false ; static
Socket s1 = null ; static
BufferedReader in= null ; static
PrintWriter out= null ; static
void set_online() { online= true ; } static
void set_offline() { online= false ; } static
void link() { try { //链接sever端 s1 = new
Socket( "127.0.0.1" , 9998 ); //实例化输入流 in= new
BufferedReader( new
InputStreamReader(s1.getInputStream())); out= new
PrintWriter(s1.getOutputStream(), true ); set_online(); System.out.println( "已连接" ); new
MyworkReader ().start(); } catch (SocketException e){ System.out.println( "无法与对方主机建立连接" ); set_offline(); System.out.println(e); } catch (IOException e){ System.out.println( "输入输出出错" ); set_offline(); System.out.println(e); } } } //创建一个进程用来写入并发送数据 class
MyworkWriter extends
Thread { public
void run() { InputStreamReader isr = new
InputStreamReader(System.in); BufferedReader br = new
BufferedReader(isr); String msg; try { while ( true ) { msg = br.readLine(); msg = msg.trim(); switch (msg) { case
"exit" : System.out.println( "exit,程序退出" ); System.exit( 0 ); break ; case
"link" : System.out.println( "link,连接远程主机" ); if (work.online) { System.out.println( "在线状态,不能重复连接" ); } else { work.link(); } break ; case
"help" : System.out.println( "help,帮助" ); System.out.println( "exit,退出程序" ); System.out.println( "link,连接主机" ); System.out.println( "close,关闭连接" ); break ; case
"close" : System.out.println( "close,关闭连接" ); work.s1.close(); break ; default : if (work.online) { work.out.println(msg); } else { System.out.println( "你已经离线状态,为您重新连接服务器." ); work.link(); if (work.online) { work.out.println(msg); } else { System.out.println( "还是不能连接,可能远程服务器已经关闭." ); } } } } } catch (IOException e) { System.out.println( "发送数据时出错" ); System.out.println(e); } } } //创建一个进程用来进行接收读取数据 class
MyworkReader extends
Thread { public
void run() { String msg; try { while ( true ) { msg = work.in.readLine(); System.out.println( "对方说:" +msg); if (msg.equals( "bye" )) { System.out.println( "对方下线,程序退出" ); work.set_offline(); break ; } } } catch (IOException e) { System.out.println( "读数据时出错,可能对方主机掉线" ); System.out.println(e); work.set_offline(); } } } |
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。