服务器端:
public class ServerTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DataOutputStream dos = null;
try {
//创建端口
ServerSocket ss = new ServerSocket(8888);
//建立监听
Socket s1 = ss.accept();
//启用一个新的线程用来读信息
new Message(s1).start();
//使用数据输出流
dos = new DataOutputStream(s1.getOutputStream());
do {
System.out.println("输入");
String a = input.nextLine();
dos.writeUTF(a);
} while (true);
} catch (IOException e) {
} finally {
try {
dos.close();
} catch (IOException e) {
// TODO自动生成的 catch 块
e.printStackTrace();
}
}
}
private static class Message extends Thread {
Socket s1 = null;
public Message(Socket socket) {
this.s1 = socket;
}
public void run() {
DataInputStream dis = null;
try {
//使用数据输入流
dis = new DataInputStream(s1.getInputStream());
do {
String str = dis.readUTF();
System.out.println("client " + str);
} while (true);
} catch (Exception e) {
e.printStackTrace();
System.out.println("关闭:"+s1.getRemoteSocketAddress());
} finally {
try {
dis.close();
} catch (IOException e) {
}
}
}
}
}
客户端:
public class ClientTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DataOutputStream dos = null;
try {
Socket s1 = new Socket("127.0.0.1", 8888);
new Message(s1).start();
dos = new DataOutputStream(s1.getOutputStream());
do {
System.out.println("输入");
String a = input.nextLine();
dos.writeUTF(a);
} while (true);
} catch (IOException e) {
} finally {
try {
dos.close();
} catch (IOException e) {
}
}
}
private static class Message extends Thread {
Socket s1 = null;
public Message(Socket socket) {
this.s1 = socket;
}
public void run() {
DataInputStream dis = null;
try {
dis = new DataInputStream(s1.getInputStream());
do {
String str = dis.readUTF();
System.out.println("server " + str);
} while (true);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
dis.close();
} catch (IOException e) {
}
}
}
}
}