当前位置:编程学习 > JAVA >>

请大家看看

两个java程序怎样实现通信,谢谢 --------------------编程问答-------------------- socket --------------------编程问答-------------------- 四个文件,望对楼主有帮助~
1.
public class ReadMsgThread implements Runnable{
private DataInputStream dis;
public ReadMsgThread(DataInputStream dis){
this.dis = dis; }
public void run() {
//不停的读数据,然后打印出来
while(true){
try {
System.out.println(dis.readUTF());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();}}}}
2.public class SendMsgThread implements Runnable{
private DataOutputStream dos;
public SendMsgThread(DataOutputStream dos){
this.dos = dos;
}
public void run() {
Scanner in = new Scanner(System.in);
while(true){
String msg = in.next();
try {
dos.writeUTF(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();}}}}
3.public class TestClient {

public static void main(String[] args) {
System.out.println("向服务器为127.0.0.1发送连接请求");
try {
Socket s = new Socket("127.0.0.1",8888);
Scanner in = new Scanner(System.in);
DataInputStream dis =
                         new DataInputStream(s.getInputStream());
DataOutputStream dos = 
                         new DataOutputStream(s.getOutputStream());
//启动一个读消息的线程,读线程需要一个输入流对象,进行读取,需要将这个对象传给线程
Thread t = new Thread(new ReadMsgThread(dis));
t.start();
Thread send = new Thread(new SendMsgThread(dos));
send.start();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();}}}
4.public class TestServer {
public static void main(String[] args) {
//创建ServerSocket对象:
try {
ServerSocket ss = new ServerSocket(8888);
System.out.println("在等待客户端的连接");
Socket s = ss.accept();//监听是否有客户端请求连接
System.out.println("接收到了客户端ip为:"  
+ s.getInetAddress().getHostAddress()+"的连接");
OutputStream out = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
DataInputStream dis = 
                           new DataInputStream(s.getInputStream());
Thread read = new Thread(new ReadMsgThread(dis));
read.start();
Thread send = new Thread(new SendMsgThread(dos));
send.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();}}}
补充:Java ,  Java相关
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,