public
class
Client {
public
static
void
main(String[] args) {
String s=
null
;
Socket mysocket;
DataInputStream in=
null
;
DataOutputStream out=
null
;
try
{
mysocket=
new
Socket(
"127.0.0.1"
,
4331
);
in=
new
DataInputStream(mysocket.getInputStream());
out=
new
DataOutputStream(mysocket.getOutputStream());
for
(
int
k=
1
;k<
100
;k=k+
2
){
out.writeUTF(
""
+k);
s=in.readUTF();
System.out.println(
"客户收到"
+s);
Thread.sleep(
500
);
}
}
catch
(Exception e) {
System.out.println(
"服务器已断开"
+e);
}
}
}
public
class
Server {
public
static
void
main(String[] args) {
ServerSocket server=
null
;
Socket you=
null
;
String s=
null
;
DataOutputStream out=
null
;
DataInputStream in=
null
;
try
{
server=
new
ServerSocket(
4331
);
}
catch
(Exception e) {
System.out.println(e);
}
try
{
System.out.println(
"等待客户呼叫"
);
you=server.accept();
out=
new
DataOutputStream(you.getOutputStream());
in=
new
DataInputStream(you.getInputStream());
while
(
true
){
s=in.readUTF();
int
m=Integer.parseInt(s);
out.writeUTF(
"你好,我是服务器"
);
out.writeUTF(
"你说的数乘2后是:"
+
2
*m);
System.out.println(
"服务器收到:"
+s);
Thread.sleep(
500
);
}
}
catch
(Exception e) {
System.out.println(
"客户端已断开"
+e);
}
}
}
很简单的服务器客户端程序