java

位置:IT落伍者 >> java >> 浏览文章

Java的socket通信的demo


发布日期:2020年06月25日
 
Java的socket通信的demo

Java代码

package testsocket;

import javaioBufferedReader;

import javaioDataInputStream;

import javaioIOException;

import javaioInputStreamReader;

import javaioOutputStream;

import javaioPrintStream;

import ServerSocket;

import Socket;

import UnknownHostException;

public class TalkMe {

public static void main(String[] args) {

Systemoutprintln(请输入:IP地址);

TalkMe talk = new TalkMe();

talklistener()start();

try {

talktalker(new BufferedReader(new InputStreamReader(Systemin))readLine())start();

} catch (IOException e) {

eprintStackTrace();

}

}

private Thread listener(){

return new Thread() {

public void run() {

DataInputStream dataIS = null;

String clientSay;

try {

ServerSocket server = new ServerSocket();

Socket socket = serveraccept();

while (true) {

dataIS = new DataInputStream(socketgetInputStream());

clientSay = dataISreadLine();

Systemoutprintln(Other say: + clientSay);

}

} catch (IOException e) {

eprintStackTrace();

}

}

};

}

private Thread talker(final String ip){

return new Thread(){

public void run() {

Socket socket = null;

InputStreamReader stdin=new InputStreamReader(Systemin);

BufferedReader br=new BufferedReader(stdin);

DataInputStream dataIS = new DataInputStream(Systemin);

OutputStream os;

PrintStream ps;

String say = ;

boolean flag = true;

while (flag) {

if (flag)

Systemoutprintln(connection );

try {

socket = new Socket(ip );

Systemoutprintln(connection ok);

flag = true;

os = socketgetOutputStream();

ps = new PrintStream(os);

while (true) {

say = dataISreadLine();

psprintln(say);

}

} catch (UnknownHostException e) {

try {

sleep();

} catch (InterruptedException e) {

eprintStackTrace();

}

} catch (IOException e) {

}

}

}

};

}

}

               

上一篇:FCKeditor编辑器在JAVA中的使用

下一篇:Java中的缓沖区