冥想法:JAVA?socket双向通讯?点对点通讯?例子

来源:百度文库 编辑:中财网 时间:2024/05/11 04:47:48
java 教程上的socket通讯只能客户端向服务器发送信息,让很多入门的朋友为难,

在这里我为朋友展示双向通讯,谢谢支持!

//以下是客户端

 

import java.io.*;
import java.net.*;
public class SockClient{               
static Socket ssock;
static String line;
static BufferedReader wt;
static PrintWriter out;
static BufferedReader in ;
public static void main(String args[]) throws IOException {
try{
ssock =new Socket("127.0.0.1",30000);
in =new BufferedReader(new InputStreamReader(ssock.getInputStream()));
out =new PrintWriter(ssock.getOutputStream());
wt=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception e){
System.out.println("连接失败");
}
threadchat t=new threadchat();
threadchat1 t1=new threadchat1();
t.start();
t1.start();


}
//线程0
static class threadchat extends Thread {
public void run(){
try{
while(true){
System.out.println("线程0启动"); 
System.out.println(in.readLine());}
}
catch(Exception e){}
}}


//线程1
static class threadchat1 extends Thread {
public void run(){
try{
while(true){
System.out.println("线程1启动");
line=wt.readLine();
out.println(line);
out.flush();}
}
catch(Exception e){}
}}

 

 

 

 

}

////以下是服务端
import java.io.*;
import java.net.*;

public class SockServer{
static String line;
static BufferedReader wt;
static PrintWriter out;
static BufferedReader in ;
public static void main(String args[]) throws IOException {
try{
ServerSocket ssock=new ServerSocket(30000);
Socket csock =ssock.accept();
in=new BufferedReader(new InputStreamReader(csock.getInputStream()));
 out=new PrintWriter(csock.getOutputStream());
wt=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception e){
System.out.println("连接出错,超哥为你提醒");
}
threadchat t=new threadchat();
threadchat1 t1=new threadchat1();
System.out.println("连接成功");  //超哥好男人
t.start();
t1.start();


}

                                  //版权保留,转摘请注明出处,chaohena1314新浪
//线程0
static class threadchat extends Thread {
public void run(){
try{
while(true){
System.out.println("线程0启动");
out.println(wt.readLine());
out.flush();}
}
catch(Exception e){}
}}

//线程1
static class threadchat1 extends Thread {
public void run(){
try{
while(true){
System.out.println("线程1启动");
line=in.readLine();
System.out.println(line);
line=in.readLine();}
}
catch(Exception e){}
}}