前面发了服务端,下面是客户端
【Socket读取】
/**
* [Product]
* netChat
* [Copyright]
* Copyright © 2012 All Rights Reserved.
* [FileName]
* ClientReader.java
* [History]
* Version Date Author Content
* -------- --------- ---------- ------------------------
* 1.0.0 2012-3-12 yangchao 最初版本
*/
package com.net.chat.client;
import java.io.DataInputStream;
import java.io.IOException;
/**
* <b>Summary: </b>
* 客户端端Socket读取类
* <b>Remarks: </b>
* 客户端端Socket读取类
*/
public class ClientReader extends Thread{
private DataInputStream dis;
public ClientReader(DataInputStream s) {
this.dis = s;
}
public void run() {
String info;
try {
while (true) {
info = dis.readUTF();
System.out.println("对方说:" + info);
if (info.equals("bye")) {
System.out.print("对方一下线");
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
【Socket写入】
/**
* [Product]
* netChat
* [Copyright]
* Copyright © 2012 All Rights Reserved.
* [FileName]
* ClientWriter.java
* [History]
* Version Date Author Content
* -------- --------- ---------- ------------------------
* 1.0.0 2012-3-12 yangchao 最初版本
*/
package com.net.chat.client;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* <b>Summary: </b>
* 客户端Socket写入类
* <b>Remarks: </b>
* 客户端Socket写入类
*/
public class ClientWriter extends Thread{
private DataOutputStream dos;
public ClientWriter(DataOutputStream s) {
this.dos = s;
}
public void run() {
String info;
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(is);
while (true) {
try {
info = bf.readLine();
dos.writeUTF(info);
if (info.equals("bye")) {
System.out.print("你已经下线");
System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
【客户端Main方法】
/**
* [Product]
* netChat
* [Copyright]
* Copyright © 2012 All Rights Reserved.
* [FileName]
* TestClient.java
* [History]
* Version Date Author Content
* -------- --------- ---------- ------------------------
* 1.0.0 2012-3-12 yangchao 最初版本
*/
package com.net.chat.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* <b>Summary: </b>
* 客户端Main方法
* <b>Remarks: </b>
* 客户端Main方法
*/
public class TestClient {
public static void main(String[] args) {
try {
Socket s1 = new Socket("127.0.0.1", 8888);
OutputStream os = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
new ClientReader(dis).start();
new ClientWriter(dos).start();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}