【Java开源代码栏目提醒】:网学会员为广大网友收集整理了,ClientThread.java,希望对大家有所帮助!
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
public class ClientThread {
final static int SERVER_PORT = 8001;
public static void main(String args[]) {
new Client("localhost", SERVER_PORT).start(); // out
new Client("localhost", SERVER_PORT+1).start(); // in
//new Client("192.168.11.16", SERVER_PORT);
//new Client("192.168.11.16", SERVER_PORT+1);
}
static class Client extends Thread {
public InputStream in;
public OutputStream out;
private Socket client;
String host;
int port;
String response, request;
BufferedReader reader, readerMe;
PrintWriter writer;
public Client(String host, int port) {
this.host = host;
this.port = port;
}
private void exec() {
try {
client = new Socket(host, port);
System.out.println("Client socket: " + client);
if(port==SERVER_PORT) out= client.getOutputStream();
else if(port==SERVER_PORT+1) in = client.getInputStream();
} catch (IOException e) {
System.err.println("IOExc : " + e);
}
if(port==SERVER_PORT) {
readerMe = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(new OutputStreamWriter(out), true);
}
else if(port==SERVER_PORT+1) reader = new BufferedReader(new InputStreamReader(in));
while(true) {
try {
if(port==SERVER_PORT) {
request = readerMe.readLine();
writer.println(request);
}
else if(port==SERVER_PORT+1) {
response = reader.readLine();
System.out.println("Server says: "+response);
}
} catch (IOException e) {
System.err.println("Bye Bye~~");
System.exit(0);
} catch (NullPointerException e2) {
}
}
}
public void run() {
exec();
}
}
}
上一篇:
ClientTest.java
下一篇:
工程硕士毕业论文写作内容有什么要求