JavaでSocket通信を実現する方法

1.サーバー側のプログラム

package Server_startnews24;
import java.io.*;
import java.net.*;

public class TCPServer {

/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
//クライアントのSocket
Socket client = null;

//クライアントの入力情報
BufferedReader buf = null;
client = new Socket(“localhost",8000);
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.println(buf.readLine());
buf.close();
client.close();

}

}

2.クライアント側のプログラム
package UDP_startnews24;
import java.io.*;
import java.net.*;
public class UDPClient {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
DatagramSocket ds = null;
DatagramPacket dp = null;

byte[] b = new byte[1024];

ds = new DatagramSocket(8000);
dp = new DatagramPacket(b,b.length);
ds.receive(dp);
String str = new String(dp.getData(),0,dp.getLength());
System.out.println(str);
}

}

Java

Posted by arkgame