Javasocket應(yīng)用實例
引導(dǎo)語:運用Java,我們可以編出很多有趣的小程序,以下是百分網(wǎng)小編分享給大家的Javasocket應(yīng)用實例,希望大家喜歡!
用于本機上的客戶端與服務(wù)器對話的'小程序:
客戶端:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Client extends Thread
{
public void Write() throws Exception
{
Socket s=new Socket("127.0.0.1",12345);
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String message="客戶端說:";
while(!(message.equals("")))
{
message=br.readLine();
System.out.println("客戶端說:"+message);
bw.write(message+"\n");
bw.flush();
}
bw.close();
s.close();
}
public void run()
{
Socket m=null;
BufferedReader dr=null;
try
{
m=new Socket("127.0.0.1",12345);
dr=new BufferedReader(new InputStreamReader(m.getInputStream()));
String msg="服務(wù)器說:";
while(!(msg.equals("")))
{
msg=dr.readLine();
System.out.println("服務(wù)器說:"+msg);
}
}
catch(Exception e){e.printStackTrace();}
finally
{
try
{
dr.close();
m.close();
}
catch(Exception e){e.printStackTrace();}
}
}
public static void main(String args[])throws Exception
{
Client c=new Client();
c.start();
c.Write();
}
}
服務(wù)器:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread
{
private ServerSocket ss=null;
public Server ()throws Exception
{
ss=new ServerSocket(12345);
}
public void Write()throws Exception
{
Socket s=ss.accept();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String message="服務(wù)器說:";
while(!(message.equals("")))
{
message=br.readLine();
System.out.println("服務(wù)器說:"+message);
bw.write(message+"\n");
bw.flush();
}
//bw.close();
s.close();
}
public void run()
{
Socket m=null;
BufferedReader dr=null;
try
{
m=ss.accept();
dr=new BufferedReader(new InputStreamReader(m.getInputStream()));
String msg="客戶端說:";
while(!(msg.equals("")))
{
msg=dr.readLine();
System.out.println("客戶端:"+msg);
}
}
catch(Exception e){e.printStackTrace();}
finally
{
try
{
dr.close();
m.close();
}
catch(Exception e){e.printStackTrace();}
}
}
public static void main(String args[])throws Exception
{
Server s=new Server();
s.start();
s.Write();
}
}