狐说霸道

树欲静而风不止

java socket 通讯

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){}
}}

阅读更多
上一篇Adobe LiveCycle Data Services ES3 solutions Explore your options
下一篇java socket点对点以及点对面编程实例
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭