62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketExample
{
/**
* @param args
*/
public static void main(String[] args)
{
try
{
ServerSocket ss = new ServerSocket(5050);
while (true)
{
Socket s = ss.accept();
Thread t = new Thread(new Dispatcher(s));
t.start();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static class Dispatcher implements Runnable
{
private DataInputStream dis;
private DataOutputStream dos;
private Socket s;
public Dispatcher(Socket s)
{
this.s = s;
try
{
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run()
{
while (true)
{
try
{
String msg = dis.readUTF();
dos.writeUTF("Hello World:" + msg);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
public void server(){ //server
try {
ss = new ServerSocket(8888);
while(boo){
s = ss.accept();
dis = new DataInputStream(s.getInputStream());
while(boo){
String str = dis.readUTF();
System.out.println(str);
//dis.close();
}
}
} catch (IOException e) {
System.out.println("connection off");
} finally {
try {if (ss != null)
ss.close();
if (s != null)
s.close();
dis.close();
}catch (IOException e1){
e1.printStackTrace();
}
}
}
private void connection(){ //client
try {
s = new Socket("127.0.0.1",8888);
System.out.println("socket connected.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}