java简单客户端服务端

import java.net.*;
import java.io.*;


public class Service
{
public static void main(String[] args)
{
InputStream in = null;
OutputStream out = null;
int port = 33333;
try {
ServerSocket ss = new ServerSocket(port);
while(true) {
Socket s = ss.accept(); 
System.out.println("a is connected!");
in = s.getInputStream();
out = s.getOutputStream();
DataInputStream din  = new DataInputStream(in);
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF("Hello Client");
String s1 = null;
if ((s1=din.readUTF()) != null) {
System.out.println(s1);
System.out.println("ip address is " + s.getInetAddress());
System.out.println("the port is " + s.getPort());
}
dout.flush();
dout.close();
din.close();
s.close();
}
} catch (IOException e) {
System.out.println("the server socket is error!");
}
}

}


import java.net.*;
import java.io.*;


public class Client
{
public static void main(String[] args)
{
InputStream in = null;
OutputStream out = null;
int port = 33333;
try {
Socket s = new Socket("localhost", port);
in = s.getInputStream();
out = s.getOutputStream();
DataInputStream din = new DataInputStream(in);
String s1 = null;
if ((s1=din.readUTF()) != null) {
System.out.println(s1);
}
DataOutputStream dout = new DataOutputStream(out);
dout.writeUTF("Hello Server !!!");
din.close();
dout.close();
s.close();
} catch (ConnectException e) {
System.out.println("the socket is connect exception !");
} catch (IOException e) {
System.out.println("the io exception is in socket!");
}
}
}


发布了145 篇原创文章 · 获赞 17 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/guichenglin/article/details/9051661