package chatSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String arg[]) throws IOException{
ServerDemo server =new ServerDemo();
server.start();
}
public void start() throws IOException{
ServerSocket ss =new ServerSocket(8899);
System.out.println("等待用户连接。。。");
Socket s=ss.accept();
System.out.println("客户连接成功:"+s.getInetAddress());
InputStream in=s.getInputStream();
OutputStream out =s.getOutputStream();
new Reader(out).start();
new Writer(in).start();
}
}
package chatSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ClientDemo {
public static void main(String args[]) throws IOException{
ClientDemo client=new ClientDemo();
client.open();
}
public void open() throws IOException{
Socket s =new Socket("localhost",8899);
InputStream in=s.getInputStream();
OutputStream out =s.getOutputStream();
new Reader(out).start();
new Writer(in).start();
}
}
package chatSocket;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Scanner;
public class Reader extends Thread{
OutputStream out;
public Reader(OutputStream out){
this.out=out;
setDaemon(true);//添加守护进程,一旦前台线程结束,加载程序运行完毕
}
public void run(){
Scanner s=new Scanner(System.in);
try{
while(true){
String str=s.nextLine();
out.write(str.getBytes());
out.write('\n');
out.flush();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
<pre name="code" class="java">package chatSocket;
import java.io.InputStream;
public class Writer extends Thread{
InputStream in;
public Writer(InputStream in){
this.in=in;
}
public void run(){
try{
int b;
while((b=in.read())!=-1){
System.out.write(b);//输出字符流
}
}catch(Exception e){
e.printStackTrace();
}
}
}
然后先启动serverDemo再启动 clientDemo
在console中输入
手打辛苦,骚年看到这里,看你骨骼精奇,气吐非凡,下面有个‘顶’字,你就顶了吧!