关于Java的Socket编程,不在啰嗦,仅作为自己学习、总结mark之用,各位收下留情。
【Socket读取】:
/**
* [Product]
* netChat
* [Copyright]
* Copyright © 2012 All Rights Reserved.
* [FileName]
* ServerReader.java
* [History]
* Version Date Author Content
* -------- --------- ---------- ------------------------
* 1.0.0 2012-3-12 yangchao 最初版本
*/
package com.net.chat.server;
import java.io.DataInputStream;
import java.io.IOException;
/**
* <b>Summary: </b>
* 服务端Socket读取类
* <b>Remarks: </b>
* 服务端Socket读取类
*/
public class ServerReader extends Thread {
private DataInputStream dis;
public ServerReader(DataInputStream dis) {
this.dis = dis;
}
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]
* ServerWriter.java
* [History]
* Version Date Author Content
* -------- --------- ---------- ------------------------
* 1.0.0 2012-3-12 yangchao 最初版本
*/
package com.net.chat.server;
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 ServerWriter extends Thread {
private DataOutputStream dos;
public ServerWriter(DataOutputStream dos) {
this.dos = dos;
}
public void run() {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader bf = new BufferedReader(isr);
String info;
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]
* TestServer.java
* [History]
* Version Date Author Content
* -------- --------- ---------- ------------------------
* 1.0.0 2012-3-12 yangchao 最初版本
*/
package com.net.chat.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* <b>Summary: </b>
* 服务端 Main 方法
* <b>Remarks: </b>
* 服务端 Main 方法
*/
public class TestServer {
public static void main(String[] args) {
try {
ServerSocket s = new ServerSocket(8888);
Socket s1 = s.accept();
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
OutputStream os = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
new ServerReader(dis).start();
new ServerWriter(dos).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}