关闭

java socket 通讯

170人阅读 评论(0) 收藏 举报
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){}
}}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:92316次
    • 积分:1171
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:82篇
    • 译文:1篇
    • 评论:16条
    最新评论