package net03;
/**
* 服务器端
*/
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
@SuppressWarnings("resource")
ServerSocket server=new ServerSocket(8888);
System.out.println("—————————服务器已启动———————————");
while(true){
Socket socket=server.accept();
new Thread(new SocketThread(socket)).start();
}
}
}
package net03;
/**
* 客户端
*/
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception, Exception {
@SuppressWarnings("resource")
Socket socket=new Socket("192.168.1.111",8888);
System.out.println("--------客户端已启动--------");
@SuppressWarnings("resource")
Scanner sc=new Scanner(System.in);
System.out.println("请输入客户端名字:");
String name=sc.next();
InputStream is=socket.getInputStream();
OutputStream os=socket.getOutputStream();
new Thread(new ReaderThread(is)).start();
new Thread(new WriteThread(os),name).start();
}
}
package net03;
import java.io.IOException;
import java.io.InputStream;
/**
* 处理输入流的线程类
* @author Administrator
*
*/
public class ReaderThread implements Runnable {
private InputStream is;
public ReaderThread(InputStream is) {
this.is = is;
}
@Override
public void run() {
try {
while(true){
byte[] b=new byte[1024];
int len=is.read(b);
String s=new String(b,0,len);
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package net03;
/**
* 处理输出流的线程类
*/
import java.io.IOException;
import java.io.OutputStream;
import java.util.Scanner;
public class WriteThread implements Runnable {
private OutputStream os;
Scanner sc=new Scanner(System.in);
public WriteThread(OutputStream os) {
this.os = os;
}
@Override
public void run() {
try {
while(true){
System.out.println("请输入:");
String mess=sc.next();
os.write((Thread.currentThread().getName()+":"+mess).getBytes());
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package net03;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* 处理socket的线程类
* @author Administrator
*
*/
public class SocketThread implements Runnable {
private Socket socket;
public SocketThread(Socket soctet) {
this.socket = soctet;
}
@Override
public void run() {
try {
InputStream is=socket.getInputStream();
OutputStream os=socket.getOutputStream();
new Thread(new ReaderThread(is)).start();
new Thread(new WriteThread(os),"服务器:").start();
} catch (IOException e) {
e.printStackTrace();
}
}
}